import { apiFetch } from './http'
import type { ApiEnvelope } from './types'

/**
 * Laravel `GET /api/v1/reports/combined` with JWT Bearer auth.
 * If your `routes/api.php` registers this elsewhere, change the path here.
 */
export type CombinedReportPayload = {
  title?: string
  subtitle?: string
  html?: string
  message?: string
  columns?: string[]
  rows?: Array<Record<string, unknown>>
  sections?: Array<{
    title?: string
    heading?: string
    rows?: Array<Record<string, unknown>>
    columns?: string[]
  }>
  [key: string]: unknown
}

type ScorePredictorApiRow = {
  student_id?: number
  school_id?: string | null
  firstname?: string | null
  lastname?: string | null
  class_section_id?: number | string | null
  fall_score?: string | number | null
  spring_score?: string | number | null
  final_average?: string | number | null
  required_spring_score?: string | number | null
  winning_risk?: string | null
  required_spring_to_pass?: string | number | null
  failure_risk?: string | null
  status?: string | null
  trophy_awarded?: boolean
  trophy_reason?: string | null
}

type ScorePredictorApiPayload = {
  ok?: boolean
  students?: ScorePredictorApiRow[]
  school_year?: string | null
  class_sections?: Array<Record<string, unknown>>
  selected_class_section_id?: number | string | null
  semester?: string | null
  message?: string | null
}

function mapScorePredictorPayload(raw: ScorePredictorApiPayload): CombinedReportPayload {
  const rows = Array.isArray(raw.students)
    ? raw.students.map((student) => ({
        school_id: student.school_id ?? '—',
        firstname: student.firstname ?? '—',
        lastname: student.lastname ?? '—',
        class_section_id: student.class_section_id ?? '—',
        fall_score: student.fall_score ?? 'N/A',
        spring_score: student.spring_score ?? 'N/A',
        final_average: student.final_average ?? 'N/A',
        required_spring_score: student.required_spring_score ?? 'N/A',
        winning_risk: student.winning_risk ?? '—',
        required_spring_to_pass: student.required_spring_to_pass ?? 'N/A',
        failure_risk: student.failure_risk ?? '—',
        status: student.status ?? '—',
        trophy_awarded: student.trophy_awarded ? 'Yes' : 'No',
        trophy_reason: student.trophy_reason ?? '—',
      }))
    : []

  const subtitleParts = [
    raw.school_year ? `School Year: ${raw.school_year}` : null,
    raw.semester ? `Semester: ${raw.semester}` : null,
    raw.selected_class_section_id ? `Class Section: ${raw.selected_class_section_id}` : null,
  ].filter(Boolean)

  return {
    title: 'Score Analysis',
    subtitle: subtitleParts.join(' • '),
    message: raw.message ?? undefined,
    columns: [
      'school_id',
      'firstname',
      'lastname',
      'class_section_id',
      'fall_score',
      'spring_score',
      'final_average',
      'required_spring_score',
      'winning_risk',
      'required_spring_to_pass',
      'failure_risk',
      'status',
      'trophy_awarded',
      'trophy_reason',
    ],
    rows,
  }
}

export function unwrapCombinedReport(raw: unknown): CombinedReportPayload | null {
  if (raw == null || typeof raw !== 'object') return null
  const o = raw as ApiEnvelope<CombinedReportPayload> & CombinedReportPayload
  if (Array.isArray((raw as ScorePredictorApiPayload).students)) {
    return mapScorePredictorPayload(raw as ScorePredictorApiPayload)
  }
  if (o.data != null && typeof o.data === 'object') {
    return o.data as CombinedReportPayload
  }
  return raw as CombinedReportPayload
}

export async function fetchCombinedReport(params?: {
  school_year?: string | null
  semester?: string | null
  student_id?: string | number | null
  class_section_id?: string | number | null
}): Promise<unknown> {
  const q = new URLSearchParams()
  if (params?.school_year) q.set('school_year', String(params.school_year))
  if (params?.semester) q.set('semester', String(params.semester))
  if (params?.student_id != null && String(params.student_id).trim() !== '') {
    q.set('student_id', String(params.student_id))
  }
  if (params?.class_section_id != null && String(params.class_section_id).trim() !== '') {
    q.set('class_section_id', String(params.class_section_id))
  }
  const qs = q.size > 0 ? `?${q.toString()}` : ''
  return apiFetch<unknown>(`/api/v1/scores/predictor${qs}`)
}
