/**
 * Teacher / admin print copy requests (legacy CI: print-requests/*).
 */
import { apiUrl } from '../lib/apiOrigin'
import { ApiHttpError, apiFetch, getStoredToken } from './http'

export type PrintRequestRow = Record<string, unknown>

export type TeacherPrintRequestsContext = {
  sundays?: string[]
  times?: string[]
  class_id?: number | null
  class_section_id?: number | null
  class_section_name?: string | null
  print_requests?: PrintRequestRow[]
}

export async function fetchTeacherPrintRequestsContext(): Promise<TeacherPrintRequestsContext> {
  return apiFetch('/api/v1/teacher/print-requests/context')
}

async function multipartRequest<T>(path: string, formData: FormData, method = 'POST'): Promise<T> {
  const headers = new Headers({ Accept: 'application/json' })
  const token = getStoredToken()
  if (token) headers.set('Authorization', `Bearer ${token}`)
  const res = await fetch(apiUrl(path), { method, headers, body: formData })
  const body: unknown = await res.json().catch(() => null)
  if (!res.ok) {
    const msg =
      typeof body === 'object' && body !== null && 'message' in body
        ? String((body as { message?: unknown }).message ?? '')
        : ''
    throw new ApiHttpError(msg || `HTTP ${res.status}`, res.status, body)
  }
  return body as T
}

export async function createPrintRequest(formData: FormData): Promise<{ ok?: boolean; message?: string }> {
  return multipartRequest('/api/v1/print-requests', formData)
}

export async function createCopyRequest(
  formData: FormData,
): Promise<{ ok?: boolean; message?: string }> {
  return multipartRequest('/api/v1/print-requests/hand-copy', formData)
}

export async function updatePrintRequest(
  requestId: number | string,
  formData: FormData,
): Promise<{ ok?: boolean; message?: string }> {
  formData.set('_method', 'PATCH')
  return multipartRequest(`/api/v1/print-requests/${encodeURIComponent(String(requestId))}`, formData)
}

export async function deletePrintRequest(requestId: number | string): Promise<{ ok?: boolean }> {
  return apiFetch(`/api/v1/print-requests/${encodeURIComponent(String(requestId))}`, {
    method: 'DELETE',
  })
}

export async function fetchAdminPrintRequests(): Promise<{ print_requests: PrintRequestRow[] }> {
  return apiFetch('/api/v1/administrator/print-requests')
}

export async function adminUpdatePrintRequestStatus(
  requestId: number | string,
  payload: { status: string; admin_id?: number | string },
): Promise<{ ok?: boolean; message?: string }> {
  return apiFetch(`/api/v1/administrator/print-requests/${encodeURIComponent(String(requestId))}/status`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  })
}

/** Authenticated download URL for uploaded job files (opened in new tab). */
export function printRequestFileUrl(requestId: number | string): string {
  return `/api/v1/print-requests/${encodeURIComponent(String(requestId))}/file`
}

export async function openPrintRequestFile(requestId: number | string): Promise<void> {
  const token = getStoredToken()
  const headers = new Headers({ Accept: '*/*' })
  if (token) headers.set('Authorization', `Bearer ${token}`)
  const res = await fetch(apiUrl(printRequestFileUrl(requestId)), { headers })
  if (!res.ok) throw new ApiHttpError(`HTTP ${res.status}`, res.status, null)
  const blob = await res.blob()
  const url = URL.createObjectURL(blob)
  window.open(url, '_blank', 'noopener')
}
