/**
 * Teacher portal API (`Views/teacher/*` parity).
 * Laravel should expose matching routes under `/api/v1/teacher/...`.
 */
import { apiFetch, getStoredToken } from './http'
import { apiUrl } from '../lib/apiOrigin'

/** Response shape for `GET /api/v1/teacher/dashboard` (extend as backend grows). */
export type TeacherDashboardPayload = {
  welcome?: string | null
  school_year?: string | null
  semester?: string | null
  counts?: Record<string, number | string | null>
  announcements?: Array<{ title?: string | null; body?: string | null; html?: string | null }>
  [key: string]: unknown
}

export async function fetchTeacherJson<T>(path: string): Promise<T> {
  const p = path.startsWith('/') ? path : `/${path}`
  return apiFetch<T>(`/api/v1/teacher${p}`)
}

/**
 * Opt-in: set `VITE_TEACHER_DASHBOARD_API=1` in `.env` when Laravel exposes
 * `GET /api/v1/teacher/dashboard`. Otherwise the SPA skips the request (avoids 404 noise).
 */
export function isTeacherDashboardApiEnabled(): boolean {
  return import.meta.env.VITE_TEACHER_DASHBOARD_API === '1'
}

export async function fetchTeacherDashboard(): Promise<TeacherDashboardPayload> {
  return fetchTeacherJson<TeacherDashboardPayload>('/dashboard')
}

export async function postTeacherJson<T>(path: string, body: unknown): Promise<T> {
  const p = path.startsWith('/') ? path : `/${path}`
  return apiFetch<T>(`/api/v1/teacher${p}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
}

export async function postTeacherMultipart<T>(path: string, formData: FormData): Promise<T> {
  const isAbsoluteApiPath = path.startsWith('/api/')
  const p = isAbsoluteApiPath ? path : path.startsWith('/') ? path : `/${path}`
  const headers = new Headers({ Accept: 'application/json' })
  const token = getStoredToken()
  if (token) headers.set('Authorization', `Bearer ${token}`)

  const url = isAbsoluteApiPath ? apiUrl(p) : apiUrl(`/api/v1/teacher${p}`)

  const res = await fetch(url, {
    method: 'POST',
    headers,
    body: formData,
  })

  const body: unknown = await res.json().catch(() => null)
  if (!res.ok) {
    let msg =
      typeof body === 'object' && body !== null && 'message' in body
        ? String((body as { message?: unknown }).message ?? '')
        : ''

    if (typeof body === 'object' && body !== null && 'errors' in body) {
      const errors = (body as { errors?: unknown }).errors
      if (errors && typeof errors === 'object') {
        const firstFieldErrors = Object.values(errors as Record<string, unknown>).find(
          (value) => Array.isArray(value) && value.length > 0,
        )
        if (Array.isArray(firstFieldErrors) && firstFieldErrors[0]) {
          msg = String(firstFieldErrors[0])
        }
      }
    }

    throw new Error(msg || `HTTP ${res.status}`)
  }

  return body as T
}
