import type {
  CreateDemandFeedbackInput,
  CreateDemandFeedbackResponse,
  DemandFeedbackHistoryResponse,
  DemandFeedbackTarget,
  VideoDiscoveryDemandDetail,
  VideoDiscoveryDemandResponse,
} from '../types/videoDiscovery'

async function errorMessage(response: Response, fallback: string): Promise<string> {
  const payload = await response.json().catch(() => null) as { detail?: string } | null
  return payload?.detail || fallback
}

export async function fetchVideoDiscoveryDemands(
  bizDt?: string | null,
): Promise<VideoDiscoveryDemandResponse> {
  const query = bizDt ? `?biz_dt=${encodeURIComponent(bizDt)}` : ''
  const res = await fetch(`/api/video-discovery/demands${query}`)
  if (!res.ok) {
    throw new Error(`加载需求找视频数据失败: ${res.status} ${res.statusText}`)
  }
  return res.json()
}

export async function fetchVideoDiscoveryDemand(
  demandGradeId: number,
): Promise<VideoDiscoveryDemandDetail> {
  const res = await fetch(`/api/video-discovery/demands/${demandGradeId}`)
  if (!res.ok) {
    throw new Error(`加载需求视频详情失败: ${res.status} ${res.statusText}`)
  }
  return res.json()
}

export async function createDemandFeedback(
  input: CreateDemandFeedbackInput,
): Promise<CreateDemandFeedbackResponse> {
  const res = await fetch('/api/video-discovery/feedback', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(input),
  })
  if (!res.ok) {
    throw new Error(await errorMessage(res, `提交反馈失败: ${res.status} ${res.statusText}`))
  }
  return res.json()
}

export async function fetchDemandFeedback(
  target: DemandFeedbackTarget,
): Promise<DemandFeedbackHistoryResponse> {
  const query = new URLSearchParams({
    target_type: target.target_type,
    demand_grade_id: String(target.demand_grade_id),
    limit: '50',
    offset: '0',
  })
  if (target.video_id) query.set('video_id', target.video_id)
  if (target.demand_video_expansion_id) {
    query.set('demand_video_expansion_id', String(target.demand_video_expansion_id))
  }
  const res = await fetch(`/api/video-discovery/feedback?${query.toString()}`)
  if (!res.ok) {
    throw new Error(await errorMessage(res, `加载反馈失败: ${res.status} ${res.statusText}`))
  }
  return res.json()
}
