// Shared CRUD shape for the ~8 near-identical HRM masters (Branch, Department,
// Designation, EmploymentType, WorkShift, HrDocumentType, LeaveType, SalaryComponent) —
// same ETag/status/list pattern as brandsApi, factored out once instead of copy-pasted 8x.
import { apiRequest, apiRequestWithETag, buildQuery } from "@/lib/api-client"
import { ApiResult, EntityStatus, PagedResponse } from "@/types/common"

export interface ListMasterParams {
  page?: number
  pageSize?: number
  q?: string
  status?: EntityStatus
}

export function createMasterApi<T, TCreate, TUpdate>(resource: string) {
  return {
    list(params: ListMasterParams = {}): Promise<PagedResponse<T>> {
      return apiRequest<PagedResponse<T>>(`/${resource}${buildQuery(params)}`)
    },
    get(id: number): Promise<ApiResult<T>> {
      return apiRequestWithETag<T>(`/${resource}/${id}`)
    },
    create(request: TCreate): Promise<ApiResult<T>> {
      return apiRequestWithETag<T>(`/${resource}`, { method: "POST", body: request })
    },
    update(id: number, request: TUpdate, ifMatch: string): Promise<ApiResult<T>> {
      return apiRequestWithETag<T>(`/${resource}/${id}`, { method: "PUT", body: request, ifMatch })
    },
    updateStatus(id: number, status: EntityStatus): Promise<void> {
      return apiRequest<void>(`/${resource}/${id}/status`, { method: "PATCH", body: { status } })
    },
  }
}
