// One typed client method per UOM endpoint (docs/11-BACKEND-PHASE1.md §2.2, FR-MD-02).
// `list` also backs the GRN/PO line UOM picker built in earlier sessions.
// In-memory sample data (lib/api/mock-data.ts) — no backend API calls.
import { PagedResponse } from "@/types/common"
import { CreateUomRequest, Uom } from "@/types/master-data"
import { allocateUomId, mockDelay, mockUoms } from "@/lib/api/mock-data"

export const uomsApi = {
  list(): Promise<PagedResponse<Uom>> {
    return mockDelay({
      items: mockUoms,
      pagination: { page: 1, pageSize: 20, totalItems: mockUoms.length, totalPages: 1 },
    })
  },

  create(request: CreateUomRequest): Promise<Uom> {
    const name = request.name.trim()
    if (!name) return Promise.reject(new Error("UOM name is required."))
    if (mockUoms.some((u) => u.name.toLowerCase() === name.toLowerCase())) {
      return Promise.reject(Object.assign(new Error(`UOM "${name}" already exists.`), { code: "SKU_DUPLICATE" }))
    }
    const uom: Uom = { uomId: allocateUomId(), name }
    mockUoms.push(uom)
    return mockDelay(uom)
  },
}
