// One typed client method per Item Type endpoint (docs/11-BACKEND-PHASE1.md §2.7; FR-MD-10).
//
// Formerly `variants.ts` / `variantCategoriesApi`. An item type is a dimension NAME
// (Color, Size, Material) and nothing more: no item references one, and there is no value
// resource. `list()` exists to populate the item builder's dropdown — the chosen values are
// encoded into the client-generated SKU and never stored (docs/10 Part C.9).
import { apiRequest, apiRequestWithETag, buildQuery } from "@/lib/api-client"
import { ApiResult, EntityStatus, PagedResponse } from "@/types/common"
import { CreateItemTypeRequest, ItemType, UpdateItemTypeRequest } from "@/types/master-data"

export interface ListItemTypesParams {
  page?: number
  pageSize?: number
  q?: string
  status?: EntityStatus
  sort?: string
}

export const itemTypesApi = {
  list(params: ListItemTypesParams = {}): Promise<PagedResponse<ItemType>> {
    return apiRequest<PagedResponse<ItemType>>(`/item-types${buildQuery(params)}`)
  },

  get(itemTypeId: number): Promise<ApiResult<ItemType>> {
    return apiRequestWithETag<ItemType>(`/item-types/${itemTypeId}`)
  },

  create(request: CreateItemTypeRequest): Promise<ApiResult<ItemType>> {
    return apiRequestWithETag<ItemType>("/item-types", { method: "POST", body: request })
  },

  /** Renaming does not touch existing items — their SKUs already encode the old value. */
  update(itemTypeId: number, request: UpdateItemTypeRequest, ifMatch: string): Promise<ApiResult<ItemType>> {
    return apiRequestWithETag<ItemType>(`/item-types/${itemTypeId}`, { method: "PUT", body: request, ifMatch })
  },

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