/**
 * Administrator invoice management & PDF (parity with CI `invoice_payment/*`).
 */
import { apiUrl } from '../lib/apiOrigin'
import { apiFetch, getStoredToken } from './http'

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

function q(searchParams: URLSearchParams): string {
  const s = searchParams.toString()
  return s ? `?${s}` : ''
}

export type InvoiceManagementRow = {
  parent_id?: number
  parent_name?: string
  enrolledKids?: { name?: string; grade?: string | number }[]
  invoice_id?: number | null
  invoice_amount?: number
  refund_amount?: number
  invoice_date?: string
}

export type InvoiceManagementResponse = {
  ok?: boolean
  schoolYears?: string[]
  schoolYear?: string
  invoices?: InvoiceManagementRow[]
}

export async function fetchInvoiceManagement(
  searchParams: URLSearchParams,
): Promise<InvoiceManagementResponse> {
  return apiFetch(`${BASE}/management${q(searchParams)}`)
}

export async function postInvoiceGenerate(parentId: number): Promise<unknown> {
  return apiFetch(`${BASE}/generate`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ parent_id: parentId }),
  })
}

/** HTML/JSON preview for browser print view (mirrors FPDF layout). */
export async function fetchInvoicePreview(invoiceId: string | number): Promise<unknown> {
  return apiFetch(`${BASE}/${invoiceId}/preview`)
}

/** Binary PDF with JWT (for tabs that cannot send Authorization). */
export async function fetchInvoicePdfBlob(invoiceId: string | number): Promise<Blob> {
  const token = getStoredToken()
  const res = await fetch(apiUrl(`${BASE}/${invoiceId}/pdf`), {
    headers: {
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      Accept: 'application/pdf',
    },
  })
  if (!res.ok) {
    const text = await res.text().catch(() => '')
    throw new Error(text || `PDF HTTP ${res.status}`)
  }
  const raw = await res.blob()
  return new Blob([await raw.arrayBuffer()], { type: 'application/pdf' })
}

export function openPdfBlobInNewTab(blob: Blob): void {
  const url = URL.createObjectURL(blob)
  window.open(url, '_blank', 'noopener,noreferrer')
  setTimeout(() => URL.revokeObjectURL(url), 120_000)
}
