// Attendance upload/validate/confirm pipeline (docs/13-BACKEND-HRM-API.md §4).
import { apiRequest, buildQuery } from "@/lib/api-client"
import { PagedResponse } from "@/types/common"
import { AttendanceBatchStatus, AttendanceRecord, AttendanceStatusValue, AttendanceUploadBatch, RowValidationStatus } from "@/types/hrm"

export interface ListAttendanceBatchesParams {
  page?: number
  pageSize?: number
  status?: AttendanceBatchStatus
  periodYear?: number
  periodMonth?: number
}

/** Direct-link download — the browser navigates/streams the binary response itself. */
export function attendanceTemplateUrl(format?: "csv"): string {
  return `/api/v1/attendance-batches/template.xlsx${format ? "?format=csv" : ""}`
}

export const attendanceApi = {
  list(params: ListAttendanceBatchesParams = {}): Promise<PagedResponse<AttendanceUploadBatch>> {
    return apiRequest<PagedResponse<AttendanceUploadBatch>>(`/attendance-batches${buildQuery(params)}`)
  },
  get(batchId: number): Promise<AttendanceUploadBatch> {
    return apiRequest<AttendanceUploadBatch>(`/attendance-batches/${batchId}`)
  },
  upload(file: File, periodStart: string, periodEnd: string): Promise<AttendanceUploadBatch> {
    const form = new FormData()
    form.append("file", file)
    form.append("PeriodStart", periodStart)
    form.append("PeriodEnd", periodEnd)
    return apiRequest<AttendanceUploadBatch>("/attendance-batches", { method: "POST", body: form })
  },

  listRecords(batchId: number, status?: RowValidationStatus): Promise<AttendanceRecord[]> {
    return apiRequest<AttendanceRecord[]>(`/attendance-batches/${batchId}/records${buildQuery({ status })}`)
  },
  updateRecord(
    batchId: number,
    recordId: number,
    request: { checkIn?: string | null; checkOut?: string | null; attendanceStatus?: AttendanceStatusValue | null; notes?: string | null }
  ): Promise<AttendanceRecord> {
    return apiRequest<AttendanceRecord>(`/attendance-batches/${batchId}/records/${recordId}`, { method: "PUT", body: request })
  },
  resolveDuplicate(batchId: number, recordId: number, action: "keep" | "discard" | "supersede"): Promise<void> {
    return apiRequest<void>(`/attendance-batches/${batchId}/resolve-duplicate`, { method: "POST", body: { recordId, action } })
  },

  validate(batchId: number): Promise<AttendanceUploadBatch> {
    return apiRequest<AttendanceUploadBatch>(`/attendance-batches/${batchId}/validate`, { method: "POST" })
  },
  confirm(batchId: number): Promise<AttendanceUploadBatch> {
    return apiRequest<AttendanceUploadBatch>(`/attendance-batches/${batchId}/confirm`, { method: "POST" })
  },
  unlock(batchId: number, reason: string): Promise<AttendanceUploadBatch> {
    return apiRequest<AttendanceUploadBatch>(`/attendance-batches/${batchId}/unlock`, { method: "POST", body: { reason } })
  },
}
