import type {
  PagedResponse,
  VideoDiscoveryCandidateRecord,
  VideoDiscoveryRunRecord,
  VideoDiscoverySearchRecord,
} from '../types/videoDiscoveryRecords'

async function readJson<T>(response: Response, message: string): Promise<T> {
  if (!response.ok) {
    const body = await response.json().catch(() => null) as { detail?: string } | null
    throw new Error(body?.detail || `${message}（${response.status}）`)
  }
  return response.json() as Promise<T>
}

function queryString(values: Record<string, string | number | null | undefined>): string {
  const query = new URLSearchParams()
  Object.entries(values).forEach(([key, value]) => {
    if (value !== null && value !== undefined && value !== '') query.set(key, String(value))
  })
  const serialized = query.toString()
  return serialized ? `?${serialized}` : ''
}

export function fetchVideoDiscoveryRuns(params: {
  bizDt?: string
  status?: string
  keyword?: string
  limit: number
  offset: number
}): Promise<PagedResponse<VideoDiscoveryRunRecord>> {
  return fetch(`/api/video-discovery/runs${queryString({
    biz_dt: params.bizDt,
    status: params.status,
    keyword: params.keyword,
    limit: params.limit,
    offset: params.offset,
  })}`).then((response) => readJson(response, '加载找视频运行失败'))
}

export function fetchVideoDiscoveryRun(runId: string): Promise<VideoDiscoveryRunRecord> {
  return fetch(`/api/video-discovery/runs/${encodeURIComponent(runId)}`)
    .then((response) => readJson(response, '加载运行详情失败'))
}

export function fetchVideoDiscoverySearches(
  runId: string,
  params: { keyword?: string; limit: number; offset: number },
): Promise<PagedResponse<VideoDiscoverySearchRecord>> {
  return fetch(
    `/api/video-discovery/runs/${encodeURIComponent(runId)}/searches${queryString(params)}`,
  ).then((response) => readJson(response, '加载搜索轨迹失败'))
}

export function fetchVideoDiscoveryCandidates(
  runId: string,
  params: { bucket?: string; keyword?: string; limit: number; offset: number },
): Promise<PagedResponse<VideoDiscoveryCandidateRecord>> {
  return fetch(
    `/api/video-discovery/runs/${encodeURIComponent(runId)}/candidates${queryString(params)}`,
  ).then((response) => readJson(response, '加载候选视频失败'))
}
