// One typed client method per stock-enquiry endpoint (docs/11-BACKEND-PHASE1.md §5.1-5.3, §5.7).
import { apiRequest, buildQuery } from "@/lib/api-client"
import { PagedResponse } from "@/types/common"
import { LedgerEntry, OnHand, ReorderAlert, ReorderRequisitionResponse, Valuation } from "@/types/stock"

export interface LedgerQuery {
  itemId?: number
  warehouseId?: number
  /** `YYYY-MM-DD`. */
  from?: string
  to?: string
  /**
   * Document-type prefix as stored on the ledger: "GRN", "ADJ", "TRF", "PRET", "CNT"
   * (Domain/DocumentTypes.cs) — not the friendly name. Pair with sourceDocId to ask
   * "what movements did this document post?".
   */
  sourceDocType?: string
  sourceDocId?: number
  page?: number
  pageSize?: number
}

export interface OnHandListParams {
  itemId?: number
  warehouseId?: number
  page?: number
  pageSize?: number
}

export const stockApi = {
  onHand(itemId: number, warehouseId: number): Promise<OnHand> {
    return apiRequest<OnHand>(`/stock/on-hand${buildQuery({ itemId, warehouseId })}`)
  },

  /** Every (item, warehouse) pair holding stock. Paged, unlike the old client-side version. */
  onHandList(params: OnHandListParams = {}): Promise<PagedResponse<OnHand>> {
    return apiRequest<PagedResponse<OnHand>>(`/stock/on-hand/list${buildQuery(params)}`)
  },

  ledger(params: LedgerQuery): Promise<PagedResponse<LedgerEntry>> {
    return apiRequest<PagedResponse<LedgerEntry>>(`/stock/ledger${buildQuery(params)}`)
  },

  valuation(itemId: number, warehouseId: number): Promise<Valuation> {
    return apiRequest<Valuation>(`/stock/valuation${buildQuery({ itemId, warehouseId })}`)
  },

  /** Items at or below their reorder point — computed on read, no stored entity (FR-STK-10). */
  reorderAlerts(warehouseId?: number, params: { page?: number; pageSize?: number } = {}): Promise<PagedResponse<ReorderAlert>> {
    return apiRequest<PagedResponse<ReorderAlert>>(`/stock/reorder-alerts${buildQuery({ warehouseId, ...params })}`)
  },

  /** Creates a draft requisition for the suggested qty; returns the full requisition. */
  createReorderRequisition(itemId: number, warehouseId: number): Promise<ReorderRequisitionResponse> {
    return apiRequest<ReorderRequisitionResponse>(
      `/stock/reorder-alerts/${itemId}/requisition${buildQuery({ warehouseId })}`,
      { method: "POST" },
    )
  },
}
