/**
 * Admin refunds list (legacy CI `refunds/list.php`).
 * Laravel: `GET /api/v1/finance/refunds` with JWT.
 */
import { apiFetch } from './http'

const BASE = '/api/v1/finance/refunds'

export type RefundListRow = Record<string, unknown>

export type RefundsListResponse = {
  refunds: RefundListRow[]
  school_year?: string | null
  semester?: string | null
  school_years?: string[]
}

function normalizeListPayload(raw: unknown): RefundsListResponse {
  const body = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}
  const inner =
    'data' in body && body.data && typeof body.data === 'object'
      ? (body.data as Record<string, unknown>)
      : body
  const list = inner.refunds ?? inner.rows ?? []
  return {
    refunds: Array.isArray(list) ? (list as RefundListRow[]) : [],
    school_year: inner.school_year != null ? String(inner.school_year) : undefined,
    semester: inner.semester != null ? String(inner.semester) : undefined,
    school_years: Array.isArray(inner.school_years)
      ? (inner.school_years as string[])
      : undefined,
  }
}

export async function fetchRefundsList(params?: {
  school_year?: string
  semester?: string
  page?: number | string
}): Promise<RefundsListResponse> {
  const qs = new URLSearchParams()
  if (params?.school_year) qs.set('school_year', params.school_year)
  if (params?.semester) qs.set('semester', params.semester)
  if (params?.page != null) qs.set('page', String(params.page))
  const suffix = qs.toString() ? `?${qs}` : ''
  const body = await apiFetch<unknown>(`${BASE}${suffix}`)
  return normalizeListPayload(body)
}
