const TOKEN_KEY = 'happy_up_token'

export function getToken(): string | null {
  return localStorage.getItem(TOKEN_KEY)
}

export function setToken(token: string) {
  localStorage.setItem(TOKEN_KEY, token)
}

export function clearToken() {
  localStorage.removeItem(TOKEN_KEY)
}

type ApiResponse<T> = {
  code: number
  message: string
  data: T
}

export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
  const headers = new Headers(init.headers)
  if (!headers.has('Content-Type') && init.body) {
    headers.set('Content-Type', 'application/json')
  }
  const token = getToken()
  if (token) {
    headers.set('Authorization', `Bearer ${token}`)
  }

  const resp = await fetch(path, { ...init, headers })
  const json = (await resp.json()) as ApiResponse<T>
  if (!resp.ok || json.code !== 0) {
    throw new Error(json.message || `HTTP ${resp.status}`)
  }
  return json.data
}

export async function login(phone: string, code: string) {
  const data = await apiFetch<{ token: string }>('/api/auth/login', {
    method: 'POST',
    body: JSON.stringify({
      loginType: 'phone_code',
      credential: phone,
      code,
    }),
  })
  setToken(data.token)
  return data
}

export type Child = {
  id: number
  name: string
  birthday: string
  gender: string
}

export async function listChildren() {
  return apiFetch<{ list: Child[] }>('/api/children')
}

export async function createUploadToken(childId: number) {
  return apiFetch<{
    uploadUrl: string
    objectKey: string
    uploadToken: string
    storage: string
    method: string
  }>('/api/videos/upload-token', {
    method: 'POST',
    body: JSON.stringify({
      childId,
      fileName: 'screening.mp4',
      contentType: 'video/mp4',
      size: 2048,
    }),
  })
}

export async function directUpload(
  uploadUrl: string,
  uploadToken: string,
  objectKey: string,
  blob: Blob,
) {
  const resp = await fetch(uploadUrl, {
    method: 'PUT',
    headers: {
      'Content-Type': 'video/mp4',
      'X-Upload-Token': uploadToken,
      'X-Object-Key': objectKey,
    },
    body: blob,
  })
  if (!resp.ok) {
    throw new Error('直传失败')
  }
}

export async function registerVideo(childId: number, objectKey: string) {
  return apiFetch<{ id: number }>('/api/videos', {
    method: 'POST',
    body: JSON.stringify({
      childId,
      objectKey,
      scene: 'front_posture',
    }),
  })
}

export async function createAnalysisTask(childId: number, videoId: number) {
  return apiFetch<{ id: number; status: string; reportId?: number }>('/api/analysis/tasks', {
    method: 'POST',
    headers: { 'Idempotency-Key': `h5-${Date.now()}` },
    body: JSON.stringify({
      childId,
      videoId,
      taskType: 'posture_screening',
    }),
  })
}

export async function getReport(reportId: number) {
  return apiFetch<{
    id?: number
    summary: string
    riskLevel: string
    metrics: Array<{ name: string; level: string; value: number }>
    recommendations?: string[]
  }>(`/api/reports/${reportId}`)
}

export async function listReports(childId: number) {
  return apiFetch<{ list: Array<{ id: number; summary: string; riskLevel: string }> }>(
    `/api/reports?childId=${childId}`,
  )
}

export function reportPdfUrl(reportId: number) {
  return `/api/reports/${reportId}/pdf`
}

export async function listTrainingPlans(childId: number) {
  return apiFetch<{
    list: Array<{
      id: number
      status: string
      detail: { goal: string; cycleDays: number; currentDay: number; exercises: Array<{ name: string }> }
    }>
  }>(`/api/training/plans?childId=${childId}`)
}

export function saveLastReportId(reportId: number) {
  sessionStorage.setItem('happy_up_last_report', String(reportId))
}

export function getLastReportId(): number | null {
  const raw = sessionStorage.getItem('happy_up_last_report')
  return raw ? Number(raw) : null
}
