// One typed client method per Item endpoint (docs/11-BACKEND-PHASE1.md §2.1, FR-MD-01/05/08).
// `list` also backs the GRN/PO/Requisition/RFQ item pickers.
import { apiRequest, apiRequestWithETag, buildQuery } from "@/lib/api-client"
import { ApiResult, EntityStatus, PagedResponse } from "@/types/common"
import {
  CreateItemRequest,
  Item,
  ItemListItem,
  ItemReorderSetting,
  TrackingMode,
  UpdateItemReorderRequest,
  UpdateItemRequest,
} from "@/types/master-data"

export interface ListItemsParams {
  page?: number
  pageSize?: number
  q?: string
  status?: EntityStatus
  categoryId?: number
  subCategoryId?: number
  brandId?: number
  trackingMode?: TrackingMode
  sort?: string
}

export const itemsApi = {
  list(params: ListItemsParams = {}): Promise<PagedResponse<ItemListItem>> {
    return apiRequest<PagedResponse<ItemListItem>>(`/items${buildQuery(params)}`)
  },

  get(itemId: number): Promise<ApiResult<Item>> {
    return apiRequestWithETag<Item>(`/items/${itemId}`)
  },

  /**
   * 400 SKU_DUPLICATE if the SKU exists; 422 CONFIG_DISABLED if subCategoryId/brandId is
   * sent while that feature is switched off; 422 if the subcategory belongs to a
   * different category.
   */
  create(request: CreateItemRequest): Promise<ApiResult<Item>> {
    return apiRequestWithETag<Item>("/items", { method: "POST", body: request })
  },

  update(itemId: number, request: UpdateItemRequest, ifMatch: string): Promise<ApiResult<Item>> {
    return apiRequestWithETag<Item>(`/items/${itemId}`, { method: "PUT", body: request, ifMatch })
  },

  /** Deactivate/reactivate — there is no DELETE (FR-MD-08). */
  updateStatus(itemId: number, status: EntityStatus): Promise<void> {
    return apiRequest<void>(`/items/${itemId}/status`, { method: "PATCH", body: { status } })
  },

  updateReorder(itemId: number, request: UpdateItemReorderRequest): Promise<{ settings: ItemReorderSetting[] }> {
    return apiRequest<{ settings: ItemReorderSetting[] }>(`/items/${itemId}/reorder`, {
      method: "PUT",
      body: request,
    })
  },
}
