// One typed client method per Purchase Order endpoint (docs/11-BACKEND-PHASE1.md §3.3,
// FR-PROC-03..07). `get`/`list` also back the GRN "against a PO" picker.
import { apiRequest, apiRequestWithETag, buildQuery } from "@/lib/api-client"
import { ApiResult, PagedResponse } from "@/types/common"
import {
  CancelPurchaseOrderRequest,
  CreatePurchaseOrderRequest,
  PurchaseOrder,
  PurchaseOrderStatus,
  PurchaseOrderSummary,
  UpdatePurchaseOrderRequest,
} from "@/types/procurement"

export interface ListPurchaseOrdersParams {
  page?: number
  pageSize?: number
  q?: string
  status?: PurchaseOrderStatus
  vendorId?: number
  sort?: string
}

/** Editable/deletable only while Draft (FR-PROC-05, revised — submitting locks the PO).
 *  The server is authoritative (409 PO_NOT_EDITABLE otherwise); this only drives UI affordances. */
export function isPoEditable(status: PurchaseOrderStatus): boolean {
  return status === "Draft"
}

export const purchaseOrdersApi = {
  list(params: ListPurchaseOrdersParams = {}): Promise<PagedResponse<PurchaseOrderSummary>> {
    return apiRequest<PagedResponse<PurchaseOrderSummary>>(`/purchase-orders${buildQuery(params)}`)
  },

  get(poId: number): Promise<PurchaseOrder> {
    return apiRequest<PurchaseOrder>(`/purchase-orders/${poId}`)
  },

  getWithETag(poId: number): Promise<ApiResult<PurchaseOrder>> {
    return apiRequestWithETag<PurchaseOrder>(`/purchase-orders/${poId}`)
  },

  /** Auto-approved on creation in Phase 1 (approvalRequired defaults false, FR-PROC-04). */
  create(request: CreatePurchaseOrderRequest): Promise<ApiResult<PurchaseOrder>> {
    return apiRequestWithETag<PurchaseOrder>("/purchase-orders", { method: "POST", body: request })
  },

  /** 409 PO_NOT_EDITABLE once fully received/closed/cancelled. */
  update(poId: number, request: UpdatePurchaseOrderRequest, ifMatch: string): Promise<ApiResult<PurchaseOrder>> {
    return apiRequestWithETag<PurchaseOrder>(`/purchase-orders/${poId}`, { method: "PUT", body: request, ifMatch })
  },

  /** No-op in Phase 1 unless approvals are enabled (FR-PROC-04). */
  approve(poId: number): Promise<PurchaseOrder> {
    return apiRequest<PurchaseOrder>(`/purchase-orders/${poId}/approve`, { method: "POST" })
  },

  /** Submit a Draft PO (Draft → Approved). 409 PO_NOT_EDITABLE if not Draft. */
  submit(poId: number): Promise<PurchaseOrder> {
    return apiRequest<PurchaseOrder>(`/purchase-orders/${poId}/submit`, { method: "POST" })
  },

  /** Delete a Draft PO. 409 PO_NOT_EDITABLE once submitted. */
  remove(poId: number): Promise<void> {
    return apiRequest<void>(`/purchase-orders/${poId}`, { method: "DELETE" })
  },

  /** 409 if any receipt exists against the PO. */
  cancel(poId: number, request: CancelPurchaseOrderRequest): Promise<PurchaseOrder> {
    return apiRequest<PurchaseOrder>(`/purchase-orders/${poId}/cancel`, { method: "POST", body: request })
  },
}
