// One typed client method per transfer endpoint (docs/11-BACKEND-PHASE1.md §5.4).
// create -> dispatch -> receive. The server consumes source FIFO layers on dispatch and
// creates the destination layer at the inherited cost on receive (cost-preserving, FR-STK-06).
import { apiRequest, buildQuery } from "@/lib/api-client"
import { PagedResponse } from "@/types/common"
import {
  CreateTransferRequest,
  DispatchTransferResponse,
  ReceiveTransferLineInput,
  ReceiveTransferResponse,
  StockTransfer,
  StockTransferSummary,
  TransferStatus,
} from "@/types/stock"

export interface ListTransfersParams {
  page?: number
  pageSize?: number
  q?: string
  status?: TransferStatus
  srcWarehouseId?: number
  destWarehouseId?: number
  sort?: string
}

export const stockTransfersApi = {
  list(params: ListTransfersParams = {}): Promise<PagedResponse<StockTransferSummary>> {
    return apiRequest<PagedResponse<StockTransferSummary>>(`/stock-transfers${buildQuery(params)}`)
  },

  get(transferId: number): Promise<StockTransfer> {
    return apiRequest<StockTransfer>(`/stock-transfers/${transferId}`)
  },

  create(request: CreateTransferRequest): Promise<StockTransfer> {
    return apiRequest<StockTransfer>("/stock-transfers", { method: "POST", body: request })
  },

  /** 409 STOCK_NEGATIVE_BLOCKED if source available < requested. */
  dispatch(transferId: number): Promise<DispatchTransferResponse> {
    return apiRequest<DispatchTransferResponse>(`/stock-transfers/${transferId}/dispatch`, { method: "POST" })
  },

  receive(transferId: number, lines: ReceiveTransferLineInput[]): Promise<ReceiveTransferResponse> {
    return apiRequest<ReceiveTransferResponse>(`/stock-transfers/${transferId}/receive`, {
      method: "POST",
      body: { lines },
    })
  },
}
