// One typed client method per Purchase Return endpoint (docs/11-BACKEND-PHASE1.md §3.4,
// FR-PROC-08). Auto-posts an outbound FIFO movement on create.
import { apiRequest, buildQuery } from "@/lib/api-client"
import { PagedResponse } from "@/types/common"
import { CreatePurchaseReturnRequest, PurchaseReturn, PurchaseReturnSummary } from "@/types/procurement"

export interface ListPurchaseReturnsParams {
  page?: number
  pageSize?: number
  q?: string
  vendorId?: number
  warehouseId?: number
  sort?: string
}

export const purchaseReturnsApi = {
  list(params: ListPurchaseReturnsParams = {}): Promise<PagedResponse<PurchaseReturnSummary>> {
    return apiRequest<PagedResponse<PurchaseReturnSummary>>(`/purchase-returns${buildQuery(params)}`)
  },

  get(returnId: number): Promise<PurchaseReturn> {
    return apiRequest<PurchaseReturn>(`/purchase-returns/${returnId}`)
  },

  /**
   * 400 REASON_CODE_REQUIRED without a reason; 422 if it is not a Return-context reason;
   * 409 STOCK_NEGATIVE_BLOCKED if the return exceeds available stock.
   */
  create(request: CreatePurchaseReturnRequest): Promise<PurchaseReturn> {
    return apiRequest<PurchaseReturn>("/purchase-returns", { method: "POST", body: request })
  },
}
