/**
 * Staff directory (legacy CI `staff/*`).
 * Expected Laravel routes under `/api/v1/administrator/staff`.
 */
import { apiFetch } from './http'

const BASE = '/api/v1/administrator/staff'

export type StaffListRow = {
  id: number
  user_id?: number
  school_id?: string | null
  firstname?: string | null
  lastname?: string | null
  email?: string | null
  phone?: string | null
  active_role?: string | null
  class_section?: string | null
  verification_issue?: boolean
}

export type StaffIndexResponse = {
  staff?: StaffListRow[]
  issues_count?: number
  school_year?: string | null
  semester?: string | null
  schoolYears?: string[]
}

export type RoleOption = { id: number; name: string }

export type StaffFormOptionsResponse = {
  roles?: RoleOption[]
}

export type StaffMemberResponse = {
  user?: Record<string, unknown> & {
    id?: number
    firstname?: string | null
    lastname?: string | null
    email?: string | null
    phone?: string | null
  }
  staff?: Record<string, unknown> & {
    firstname?: string | null
    lastname?: string | null
    email?: string | null
    phone?: string | null
  }
}

export async function fetchStaffIndex(params?: {
  school_year?: string
  semester?: string
}): Promise<StaffIndexResponse> {
  const qs = new URLSearchParams()
  if (params?.school_year) qs.set('school_year', params.school_year)
  if (params?.semester) qs.set('semester', params.semester)
  const suffix = qs.toString() ? `?${qs}` : ''
  return apiFetch(`${BASE}${suffix}`)
}

export async function fetchStaffFormOptions(): Promise<StaffFormOptionsResponse> {
  return apiFetch(`${BASE}/form-options`)
}

export async function fetchStaffMember(id: number): Promise<StaffMemberResponse> {
  return apiFetch(`${BASE}/${id}`)
}

export async function createStaff(payload: {
  firstname: string
  lastname: string
  email: string
  password: string
  role_id: number
}): Promise<{ ok?: boolean; message?: string }> {
  return apiFetch(`${BASE}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  })
}

export async function updateStaff(
  id: number,
  payload: { firstname: string; lastname: string; email: string; phone?: string },
): Promise<{ ok?: boolean; message?: string }> {
  return apiFetch(`${BASE}/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  })
}
