// Payroll runs, statutory settings, tax slabs, payslips (docs/13-BACKEND-HRM-API.md §6).
import { apiRequest, buildQuery } from "@/lib/api-client"
import { PagedResponse } from "@/types/common"
import { Payslip, PayrollLine, PayrollLineDetail, PayrollRun, PayrollRunStatus, PayrollStatutorySetting, TaxSlab } from "@/types/hrm"

export interface ListPayrollRunsParams {
  page?: number
  pageSize?: number
  periodYear?: number
  periodMonth?: number
  status?: PayrollRunStatus
}

export interface GeneratePayrollRunRequest {
  periodYear: number
  periodMonth: number
  branchId?: number | null
}

export const payrollRunsApi = {
  list(params: ListPayrollRunsParams = {}): Promise<PagedResponse<PayrollRun>> {
    return apiRequest<PagedResponse<PayrollRun>>(`/payroll-runs${buildQuery(params)}`)
  },
  get(payrollRunId: number): Promise<PayrollRun> {
    return apiRequest<PayrollRun>(`/payroll-runs/${payrollRunId}`)
  },
  listLines(payrollRunId: number): Promise<PayrollLine[]> {
    return apiRequest<PayrollLine[]>(`/payroll-runs/${payrollRunId}/lines`)
  },
  getLine(payrollRunId: number, lineId: number): Promise<PayrollLineDetail> {
    return apiRequest<PayrollLineDetail>(`/payroll-runs/${payrollRunId}/lines/${lineId}`)
  },
  generate(request: GeneratePayrollRunRequest): Promise<PayrollRun> {
    return apiRequest<PayrollRun>("/payroll-runs", { method: "POST", body: request })
  },
  approve(payrollRunId: number): Promise<PayrollRun> {
    return apiRequest<PayrollRun>(`/payroll-runs/${payrollRunId}/approve`, { method: "POST" })
  },
  lock(payrollRunId: number): Promise<PayrollRun> {
    return apiRequest<PayrollRun>(`/payroll-runs/${payrollRunId}/lock`, { method: "POST" })
  },
  unlock(payrollRunId: number, reason: string): Promise<PayrollRun> {
    return apiRequest<PayrollRun>(`/payroll-runs/${payrollRunId}/unlock`, { method: "POST", body: { reason } })
  },
  generatePayslips(payrollRunId: number): Promise<Payslip[]> {
    return apiRequest<Payslip[]>(`/payroll-runs/${payrollRunId}/generate-payslips`, { method: "POST" })
  },
}

export const payrollStatutorySettingsApi = {
  list(): Promise<PayrollStatutorySetting[]> {
    return apiRequest<PayrollStatutorySetting[]>("/payroll-statutory-settings")
  },
  create(request: Omit<PayrollStatutorySetting, "payrollStatutorySettingId" | "effectiveTo">): Promise<PayrollStatutorySetting> {
    return apiRequest<PayrollStatutorySetting>("/payroll-statutory-settings", { method: "POST", body: request })
  },
}

export const taxSlabsApi = {
  list(): Promise<TaxSlab[]> {
    return apiRequest<TaxSlab[]>("/tax-slabs")
  },
  create(request: Omit<TaxSlab, "taxSlabId" | "effectiveTo">): Promise<TaxSlab> {
    return apiRequest<TaxSlab>("/tax-slabs", { method: "POST", body: request })
  },
}

export function payslipViewUrl(payslipId: number): string {
  return `/api/v1/payslips/${payslipId}/view`
}
