// One typed client method per Variant Category endpoint, mirroring lib/api/brands.ts.
// In-memory sample data (lib/api/mock-data.ts) — no backend API calls.
import { PagedResponse } from "@/types/common"
import { CreateVariantCategoryRequest, UpdateVariantCategoryRequest, VariantCategory } from "@/types/master-data"
import { allocateVariantCategoryId, mockVariantCategories, mockDelay } from "@/lib/api/mock-data"

export const variantCategoriesApi = {
  list(): Promise<PagedResponse<VariantCategory>> {
    const items = [...mockVariantCategories].sort((a, b) => a.name.localeCompare(b.name))
    return mockDelay({
      items,
      pagination: { page: 1, pageSize: items.length || 1, totalItems: items.length, totalPages: 1 },
    })
  },

  create(request: CreateVariantCategoryRequest): Promise<VariantCategory> {
    const name = request.name.trim()
    if (!name) return Promise.reject(new Error("Category name is required."))
    if (mockVariantCategories.some((c) => c.name.toLowerCase() === name.toLowerCase())) {
      return Promise.reject(new Error(`Variant category "${name}" already exists.`))
    }
    const category: VariantCategory = {
      variantCategoryId: allocateVariantCategoryId(),
      name,
      createdAt: new Date().toISOString(),
    }
    mockVariantCategories.push(category)
    return mockDelay(category)
  },

  update(variantCategoryId: number, request: UpdateVariantCategoryRequest): Promise<VariantCategory> {
    const name = request.name.trim()
    if (!name) return Promise.reject(new Error("Category name is required."))
    const category = mockVariantCategories.find((c) => c.variantCategoryId === variantCategoryId)
    if (!category) return Promise.reject(new Error("Variant category not found."))
    if (mockVariantCategories.some((c) => c.variantCategoryId !== variantCategoryId && c.name.toLowerCase() === name.toLowerCase())) {
      return Promise.reject(new Error(`Variant category "${name}" already exists.`))
    }
    category.name = name
    return mockDelay(category)
  },

  remove(variantCategoryId: number): Promise<void> {
    const index = mockVariantCategories.findIndex((c) => c.variantCategoryId === variantCategoryId)
    if (index === -1) return Promise.reject(new Error("Variant category not found."))
    mockVariantCategories.splice(index, 1)
    return mockDelay(undefined)
  },
}
