/** 手动修正看板数据 API */

export interface CombatLossesRow {
  side: string
  bases_destroyed: number
  bases_damaged: number
  personnel_killed: number
  personnel_wounded: number
  civilian_killed?: number
  civilian_wounded?: number
  aircraft: number
  warships: number
  armor: number
  vehicles: number
  drones?: number
  missiles?: number
  helicopters?: number
  submarines?: number
  tanks?: number
  carriers?: number
  civilian_ships?: number
  airport_port?: number
}

export interface KeyLocationRow {
  id: number
  side: string
  name: string
  lat: number
  lng: number
  type?: string | null
  region?: string | null
  status?: string | null
  damage_level?: number | null
}

export interface SituationUpdateRow {
  id: string
  timestamp: string
  category: string
  summary: string
  severity: string
}

export interface ForceSummaryRow {
  side: string
  total_assets: number
  personnel: number
  naval_ships: number
  aircraft: number
  ground_units: number
  uav: number
  missile_consumed: number
  missile_stock: number
}

export interface DisplayStatsRow {
  overrideEnabled?: boolean
  viewers: number
  cumulative: number
  shareCount: number
  likeCount: number
  feedbackCount: number
}

export interface AnimationConfigRow {
  strikeCutoffDays: number
}

export interface CrawlerConfigRow {
  rssIntervalSec: number
}

export interface FeedbackRow {
  id: number
  content: string
  ip: string | null
  created_at: string
}

export interface EditRawData {
  combatLosses: { us: CombatLossesRow | null; iran: CombatLossesRow | null }
  keyLocations: { us: KeyLocationRow[]; iran: KeyLocationRow[] }
  situationUpdates: SituationUpdateRow[]
  forceSummary: { us: ForceSummaryRow | null; iran: ForceSummaryRow | null }
  displayStats?: DisplayStatsRow
  animationConfig?: AnimationConfigRow
  crawlerConfig?: CrawlerConfigRow
}

export async function fetchEditRaw(): Promise<EditRawData> {
  const res = await fetch('/api/edit/raw', { cache: 'no-store' })
  if (!res.ok) throw new Error(`API error: ${res.status}`)
  return res.json()
}

export async function putCombatLosses(side: 'us' | 'iran', body: Partial<CombatLossesRow>): Promise<void> {
  const res = await fetch('/api/edit/combat-losses', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ side, ...body }),
  })
  if (!res.ok) {
    const e = await res.json().catch(() => ({}))
    throw new Error((e as { error?: string }).error || res.statusText)
  }
}

export async function patchKeyLocation(id: number, body: Partial<KeyLocationRow>): Promise<void> {
  const res = await fetch(`/api/edit/key-location/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
  if (!res.ok) {
    const e = await res.json().catch(() => ({}))
    throw new Error((e as { error?: string }).error || res.statusText)
  }
}

export async function postSituationUpdate(body: {
  id?: string
  timestamp?: string
  category: string
  summary: string
  severity?: string
}): Promise<{ id: string }> {
  const res = await fetch('/api/edit/situation-update', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
  if (!res.ok) {
    const e = await res.json().catch(() => ({}))
    throw new Error((e as { error?: string }).error || res.statusText)
  }
  return res.json()
}

export async function deleteSituationUpdate(id: string): Promise<void> {
  const res = await fetch(`/api/edit/situation-update/${encodeURIComponent(id)}`, { method: 'DELETE' })
  if (!res.ok) {
    const e = await res.json().catch(() => ({}))
    throw new Error((e as { error?: string }).error || res.statusText)
  }
}

export async function putForceSummary(side: 'us' | 'iran', body: Partial<ForceSummaryRow>): Promise<void> {
  const res = await fetch('/api/edit/force-summary', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ side, ...body }),
  })
  if (!res.ok) {
    const e = await res.json().catch(() => ({}))
    throw new Error((e as { error?: string }).error || res.statusText)
  }
}

/** 传 null 的字段会清除覆盖，改回实时统计 */
/** 传 clearOverride: true 可关闭覆盖、恢复实时统计 */
export async function putDisplayStats(
  body: Partial<{ [K in keyof DisplayStatsRow]: number | null }> & { clearOverride?: boolean }
): Promise<void> {
  const res = await fetch('/api/edit/display-stats', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
  if (!res.ok) {
    const e = await res.json().catch(() => ({}))
    throw new Error((e as { error?: string }).error || res.statusText)
  }
}

export async function putAnimationConfig(body: Partial<AnimationConfigRow>): Promise<void> {
  const res = await fetch('/api/edit/animation-config', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
  if (!res.ok) {
    const e = await res.json().catch(() => ({}))
    throw new Error((e as { error?: string }).error || res.statusText)
  }
}

export async function putCrawlerConfig(body: { rssIntervalSec: number }): Promise<void> {
  const res = await fetch('/api/edit/crawler-config', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
  if (!res.ok) {
    const e = await res.json().catch(() => ({}))
    throw new Error((e as { error?: string }).error || res.statusText)
  }
}

export async function fetchFeedbackList(): Promise<{ list: FeedbackRow[] }> {
  const res = await fetch('/api/edit/feedback', { cache: 'no-store' })
  if (!res.ok) throw new Error('获取留言失败')
  return res.json()
}
