/**
 * Staff directory.
 */
import { apiFetch } from './http'

const BASE = '/api/v1/staff'

function unwrapData<T>(body: T | { data?: T }): T {
  if (body && typeof body === 'object' && 'data' in body && (body as { data?: T }).data != null) {
    return (body as { data?: T }).data as T
  }
  return body as T
}

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
  status?: string | null
}

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

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

export type StaffFormOptionsResponse = {
  roles?: RoleOption[]
  statuses?: Array<{ value: string; label: string }>
  school_year?: string | null
  is_read_only_year?: boolean
}

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
  role?: string
  status?: string
  search?: string
  page?: number
  per_page?: number
}): 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)
  if (params?.role) qs.set('role', params.role)
  if (params?.status) qs.set('status', params.status)
  if (params?.search) qs.set('search', params.search)
  if (params?.page) qs.set('page', String(params.page))
  if (params?.per_page) qs.set('per_page', String(params.per_page))
  const suffix = qs.toString() ? `?${qs}` : ''
  return unwrapData(await apiFetch(`${BASE}${suffix}`))
}

export async function fetchStaffFormOptions(params?: { school_year?: string }): Promise<StaffFormOptionsResponse> {
  const qs = new URLSearchParams()
  if (params?.school_year) qs.set('school_year', params.school_year)
  return unwrapData(await apiFetch(`${BASE}/form-options${qs.toString() ? `?${qs}` : ''}`))
}

export async function fetchStaffMember(id: number, params?: { school_year?: string }): Promise<StaffMemberResponse> {
  const qs = new URLSearchParams()
  if (params?.school_year) qs.set('school_year', params.school_year)
  return unwrapData(await apiFetch(`${BASE}/${id}${qs.toString() ? `?${qs}` : ''}`))
}

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