import { normalizeNextPath } from './auth/next-path'

export type DownloadPlatformKey = 'windows' | 'macos' | 'linux'

const DOWNLOAD_PLATFORM_LABELS: Record<DownloadPlatformKey, string> = {
  windows: 'Windows',
  macos: 'macOS',
  linux: 'Linux',
}

const DOWNLOAD_PLATFORM_KEYS = Object.keys(DOWNLOAD_PLATFORM_LABELS) as DownloadPlatformKey[]

export function normalizeDownloadPlatform(value: string | null | undefined): DownloadPlatformKey | null {
  const normalized = String(value || '').trim().toLowerCase()
  if (!normalized) {
    return null
  }

  return DOWNLOAD_PLATFORM_KEYS.includes(normalized as DownloadPlatformKey)
    ? (normalized as DownloadPlatformKey)
    : null
}

export function getDownloadPlatformLabel(platform: DownloadPlatformKey): string {
  return DOWNLOAD_PLATFORM_LABELS[platform]
}

export function buildProtectedDownloadPath(platform?: DownloadPlatformKey | null): string {
  const normalizedPlatform = normalizeDownloadPlatform(platform)
  if (!normalizedPlatform) {
    return '/app/downloads'
  }

  const params = new URLSearchParams({ platform: normalizedPlatform })
  return `/app/downloads?${params.toString()}`
}

export function buildSupportPath(topic?: string): string {
  const normalizedTopic = String(topic || '').trim()
  if (!normalizedTopic) {
    return '/support'
  }

  const params = new URLSearchParams({ topic: normalizedTopic })
  return `/support?${params.toString()}`
}

function buildAuthPath(mode: 'login' | 'register', nextPath: string | null | undefined, fallback = '/app') {
  const normalizedNextPath = normalizeNextPath(nextPath, fallback)
  return `/${mode}?next=${encodeURIComponent(normalizedNextPath)}`
}

export function buildLoginPath(nextPath?: string | null, fallback?: string): string {
  return buildAuthPath('login', nextPath, fallback)
}

export function buildRegisterPath(nextPath?: string | null, fallback?: string): string {
  return buildAuthPath('register', nextPath, fallback)
}

export function isExternalHref(value: string): boolean {
  return /^[a-z][a-z0-9+.-]*:/i.test(value)
}
