import { apiFetch } from './http'

export type BadgeScanLogRow = {
  id: number
  user_id: number | null
  card_id: string
  scan_time: string
  school_year: string | null
  semester: string | null
  user_firstname: string | null
  user_lastname: string | null
  student_firstname: string | null
  student_lastname: string | null
}

export type BadgeScanLogsResponse = {
  logs: BadgeScanLogRow[]
}

function unwrap(body: unknown): unknown {
  if (body === null || body === undefined || typeof body !== 'object') return body
  const o = body as Record<string, unknown>
  if ('data' in o && o.data !== null && typeof o.data === 'object') return o.data
  return body
}

export async function fetchBadgeScanLogs(): Promise<BadgeScanLogsResponse> {
  const raw = await apiFetch<unknown>('/api/v1/badge_scan/logs')
  const data = unwrap(raw) as BadgeScanLogsResponse
  return { logs: Array.isArray(data?.logs) ? data.logs : [] }
}

export function displayNameOf(row: BadgeScanLogRow): string {
  const userFull = [row.user_firstname, row.user_lastname].filter(Boolean).join(' ').trim()
  if (userFull) return userFull
  const stuFull = [row.student_firstname, row.student_lastname].filter(Boolean).join(' ').trim()
  if (stuFull) return stuFull
  return row.card_id
}
