/**
 * Incidents / flags API (parity with CI `flags/*` + JSON routes in Laravel).
 * Expected base: `/api/v1/administrator/flags/...` with JWT.
 */
import { apiFetch } from './http'

export type IncidentFlagRow = {
  id?: number
  flag_state?: string
  student_name?: string
  grade?: string
  flag?: string
  open_description?: string
  close_description?: string
  cancel_description?: string
  flag_datetime?: string | null
  action_taken?: string | null
  updated_by_open_name?: string | null
  updated_by_open?: string | number | null
  updated_by_closed_name?: string | null
  updated_by_closed?: string | number | null
  updated_by_canceled_name?: string | null
  updated_by_canceled?: string | number | null
}

export type IncidentLogRow = {
  flag?: string
  flag_state?: string
  flag_datetime?: string | null
  open_description?: string
  close_description?: string
  cancel_description?: string
  action_taken?: string | null
}

export type IncidentAnalysisStudent = {
  student_name?: string
  grade?: string
  total?: number
  open?: number
  closed?: number
  canceled?: number
  last_incident?: string | null
  logs?: IncidentLogRow[]
}

export type GradeOption = { id: number; name: string }

function qs(searchParams: URLSearchParams): string {
  const sy = searchParams.get('school_year')
  const sem = searchParams.get('semester')
  const q = new URLSearchParams()
  if (sy) q.set('school_year', sy)
  if (sem) q.set('semester', sem)
  const s = q.toString()
  return s ? `?${s}` : ''
}

function unwrapFlags(body: unknown): unknown[] {
  if (Array.isArray(body)) return body
  if (body && typeof body === 'object') {
    const o = body as { flags?: unknown; data?: { flags?: unknown } }
    const raw = o.flags ?? o.data?.flags
    if (Array.isArray(raw)) return raw
  }
  return []
}

function unwrapStudents(body: unknown): unknown[] {
  if (Array.isArray(body)) return body
  if (body && typeof body === 'object') {
    const o = body as { students?: unknown; data?: { students?: unknown } }
    const raw = o.students ?? o.data?.students
    if (Array.isArray(raw)) return raw
  }
  return []
}

export async function fetchFlagsProcessed(searchParams: URLSearchParams): Promise<IncidentFlagRow[]> {
  const body = await apiFetch<{ flags?: IncidentFlagRow[]; data?: { flags?: IncidentFlagRow[] } }>(
    `/api/v1/administrator/flags/processed${qs(searchParams)}`,
  )
  return unwrapFlags(body) as IncidentFlagRow[]
}

export async function fetchFlagsPending(searchParams: URLSearchParams): Promise<IncidentFlagRow[]> {
  const body = await apiFetch<{ flags?: IncidentFlagRow[]; data?: { flags?: IncidentFlagRow[] } }>(
    `/api/v1/administrator/flags/pending${qs(searchParams)}`,
  )
  return unwrapFlags(body) as IncidentFlagRow[]
}

export async function fetchIncidentAnalysis(
  searchParams: URLSearchParams,
): Promise<IncidentAnalysisStudent[]> {
  const body = await apiFetch<{
    students?: IncidentAnalysisStudent[]
    data?: { students?: IncidentAnalysisStudent[] }
  }>(`/api/v1/administrator/flags/incident-analysis${qs(searchParams)}`)
  return unwrapStudents(body) as IncidentAnalysisStudent[]
}

export async function fetchFlagsFormMeta(): Promise<{ grades: GradeOption[] }> {
  return apiFetch<{ grades: GradeOption[] }>('/api/v1/administrator/flags/form-meta')
}

export async function fetchStudentsByGrade(gradeId: number): Promise<Array<{ id: number; name: string }>> {
  return apiFetch<Array<{ id: number; name: string }>>(
    `/api/v1/administrator/flags/grades/${gradeId}/students`,
  )
}

export async function createIncidentFlag(payload: {
  grade: number | string
  student: number | string
  flag: string
  description: string
  school_year?: string
  semester?: string
}): Promise<{ message?: string } | unknown> {
  return apiFetch(`/api/v1/administrator/flags`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  })
}

export async function closeIncidentFlag(
  id: number,
  body: { state_description: string; action_taken: string },
): Promise<unknown> {
  return apiFetch(`/api/v1/administrator/flags/${id}/close`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export async function cancelIncidentFlag(
  id: number,
  body: { state_description: string; action_taken: string },
): Promise<unknown> {
  return apiFetch(`/api/v1/administrator/flags/${id}/cancel`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}
