import { apiFetch } from './http'

export type ParentProfileSummary = {
  id: number
  firstname?: string | null
  lastname?: string | null
  email?: string | null
  cellphone?: string | null
  is_active?: boolean
  families_count?: number
  selected_year_students_count?: number
  balance?: number
  positive_unpaid_balance?: number
  credit_balance?: number
  primary_family?: { id?: number; household_name?: string | null } | null
}

export type ParentProfileDetail = {
  school_year: string
  read_only: boolean
  parent: Record<string, unknown> | null
  families: Record<string, unknown>[]
  students: Record<string, unknown>[]
  emergency_contacts: Record<string, unknown>[]
  invoices: Record<string, unknown>[]
  payments: Record<string, unknown>[]
  finance_summary: Record<string, unknown>
}

type Envelope<T> = { data?: T }

function unwrap<T>(response: T | Envelope<T>): T {
  if (response && typeof response === 'object' && 'data' in response) {
    return (response as Envelope<T>).data as T
  }
  return response as T
}

export async function fetchParentProfiles(params: {
  schoolYear: string
  q?: string
  page?: number
  perPage?: number
}): Promise<{
  school_year: string
  read_only: boolean
  parents: ParentProfileSummary[]
  pagination: { page: number; per_page: number; total: number }
}> {
  const query = new URLSearchParams()
  query.set('school_year', params.schoolYear)
  if (params.q?.trim()) query.set('q', params.q.trim())
  if (params.page) query.set('page', String(params.page))
  if (params.perPage) query.set('per_page', String(params.perPage))
  return unwrap(await apiFetch(`/api/v1/parent-profiles?${query.toString()}`))
}

export async function fetchParentProfile(parentId: number, schoolYear: string): Promise<ParentProfileDetail> {
  const query = new URLSearchParams({ school_year: schoolYear })
  return unwrap(await apiFetch(`/api/v1/parent-profiles/${parentId}?${query.toString()}`))
}

export async function updateParentProfile(parentId: number, schoolYear: string, payload: Record<string, unknown>): Promise<ParentProfileDetail> {
  const query = new URLSearchParams({ school_year: schoolYear })
  return unwrap(await apiFetch(`/api/v1/parent-profiles/${parentId}?${query.toString()}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ...payload, school_year: schoolYear }),
  }))
}
