const DEFAULT_BASE_URL = 'https://s.kwaixiaodian.com'
const DEFAULT_REFERER_PATH = '/zone/industry/voucher/verify-list'
const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36'

export type KuaishouEticketConfigInput = {
  enabled?: boolean
  baseUrl?: string
  cookie?: string
  timeoutMs?: number | string
  infoPath?: string
  detailPath?: string
  consumePath?: string
  refererPath?: string
  userAgent?: string
}

export type KuaishouEticketConfig = {
  enabled: boolean
  baseUrl: string
  cookie: string
  timeoutMs: number
  infoPath: string
  detailPath: string
  consumePath: string
  refererPath: string
  userAgent: string
}

type HeaderInput = {
  baseUrl?: string
  refererPath?: string
  userAgent?: string
  cookie?: string
  contentType?: string
  extra?: Record<string, unknown>
}

export function resolveKuaishouEticketConfig(overrides: KuaishouEticketConfigInput = {}): KuaishouEticketConfig {
  return {
    enabled: overrides.enabled !== false,
    baseUrl: normalizeBaseUrl(overrides.baseUrl || DEFAULT_BASE_URL) || DEFAULT_BASE_URL,
    cookie: String(overrides.cookie || '').trim(),
    timeoutMs: normalizePositiveInteger(overrides.timeoutMs, 8000),
    infoPath: normalizePath(overrides.infoPath, '/gateway/pc/workbench/service/stable/info'),
    detailPath: normalizePath(overrides.detailPath, '/gateway/industry/eticket/consume/detail'),
    consumePath: normalizePath(overrides.consumePath, '/gateway/industry/eticket/consume'),
    refererPath: normalizePath(overrides.refererPath, DEFAULT_REFERER_PATH),
    userAgent: String(overrides.userAgent || DEFAULT_USER_AGENT).trim() || DEFAULT_USER_AGENT,
  }
}

export function buildKuaishouEticketUrl(baseUrl: unknown, pathname: unknown): URL {
  return new URL(normalizePath(pathname, '/'), normalizeBaseUrl(baseUrl) || DEFAULT_BASE_URL)
}

export function buildKuaishouEticketHeaders({
  baseUrl = DEFAULT_BASE_URL,
  refererPath = DEFAULT_REFERER_PATH,
  userAgent = DEFAULT_USER_AGENT,
  cookie = '',
  contentType = 'application/json',
  extra = {},
}: HeaderInput = {}): Record<string, string> {
  return {
    accept: 'application/json',
    'accept-language': 'zh-CN,zh;q=0.9',
    ...(contentType ? { 'content-type': contentType } : {}),
    kpf: 'PC_WEB',
    kpn: 'KWAIXIAODIAN',
    origin: normalizeBaseUrl(baseUrl) || DEFAULT_BASE_URL,
    referer: buildKuaishouEticketUrl(baseUrl, refererPath).toString(),
    'user-agent': String(userAgent || DEFAULT_USER_AGENT).trim() || DEFAULT_USER_AGENT,
    ...(String(cookie || '').trim() ? { cookie: String(cookie || '').trim() } : {}),
    ...normalizeHeaderMap(extra),
  }
}

function normalizeBaseUrl(value: unknown): string {
  return String(value || '').trim().replace(/\/+$/, '')
}

function normalizePath(value: unknown, fallback: string): string {
  const normalized = String(value || '').trim()
  if (!normalized) {
    return fallback
  }

  return normalized.startsWith('/') ? normalized : `/${normalized}`
}

function normalizePositiveInteger(value: unknown, fallback: number): number {
  const parsed = Number(value)
  return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback
}

function normalizeHeaderMap(extra: unknown): Record<string, string> {
  if (!extra || typeof extra !== 'object') {
    return {}
  }

  return Object.fromEntries(
    Object.entries(extra)
      .map(([key, value]) => [String(key || '').trim().toLowerCase(), String(value || '').trim()])
      .filter(([key, value]) => key && value),
  )
}
