// One typed client method per count endpoint (docs/11-BACKEND-PHASE1.md §5.6).
// create (snapshots system qty) -> enterCounts -> post (creates the variance adjustment).
import { apiRequest, buildQuery } from "@/lib/api-client"
import { PagedResponse } from "@/types/common"
import {
  CountStatus,
  CreateCountRequest,
  EnterCountsRequest,
  PostCountResponse,
  StockCount,
  StockCountSummary,
} from "@/types/stock"

export interface ListCountsParams {
  page?: number
  pageSize?: number
  q?: string
  status?: CountStatus
  warehouseId?: number
  sort?: string
}

export const stockCountsApi = {
  list(params: ListCountsParams = {}): Promise<PagedResponse<StockCountSummary>> {
    return apiRequest<PagedResponse<StockCountSummary>>(`/stock-counts${buildQuery(params)}`)
  },

  get(countId: number): Promise<StockCount> {
    return apiRequest<StockCount>(`/stock-counts/${countId}`)
  },

  create(request: CreateCountRequest): Promise<StockCount> {
    return apiRequest<StockCount>("/stock-counts", { method: "POST", body: request })
  },

  /** Returns the whole count (with server-computed variance), not just the lines. */
  enterCounts(countId: number, request: EnterCountsRequest): Promise<StockCount> {
    return apiRequest<StockCount>(`/stock-counts/${countId}/counts`, { method: "PUT", body: request })
  },

  /** Posts the variance adjustment and closes the count. `adjustmentId` is null if there was no variance. */
  post(countId: number): Promise<PostCountResponse> {
    return apiRequest<PostCountResponse>(`/stock-counts/${countId}/post`, { method: "POST" })
  },
}
