// One typed client method per Category endpoint (docs/11-BACKEND-PHASE1.md §2.3, FR-MD-04).
// In-memory sample data (lib/api/mock-data.ts) — no backend API calls.
import { PagedResponse } from "@/types/common"
import { Category, CreateCategoryRequest, UpdateCategoryRequest } from "@/types/master-data"
import { allocateCategoryId, mockCategories, mockDelay } from "@/lib/api/mock-data"

export interface ListCategoriesParams {
  page?: number
  pageSize?: number
  q?: string
  sortOrder?: "asc" | "desc"
}

export const categoriesApi = {
  list(params: ListCategoriesParams = {}): Promise<PagedResponse<Category>> {
    const term = params.q?.trim().toLowerCase()
    const sortOrder = params.sortOrder ?? "asc"
    const filtered = mockCategories
      .filter((c) => !term || c.name.toLowerCase().includes(term))
      .sort((a, b) => (sortOrder === "asc" ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)))

    const page = params.page ?? 1
    const pageSize = params.pageSize ?? 5
    const start = (page - 1) * pageSize
    const items = filtered.slice(start, start + pageSize)
    const totalItems = filtered.length
    const totalPages = pageSize <= 0 ? 0 : Math.ceil(totalItems / pageSize)

    return mockDelay({
      items,
      pagination: { page, pageSize, totalItems, totalPages },
    })
  },

  create(request: CreateCategoryRequest): Promise<Category> {
    const name = request.name.trim()
    if (!name) return Promise.reject(new Error("Category name is required."))
    const parentId = request.parentId ?? null
    if (parentId !== null && !mockCategories.some((c) => c.categoryId === parentId)) {
      return Promise.reject(new Error("Selected parent category does not exist."))
    }
    const category: Category = { categoryId: allocateCategoryId(), name, parentId, createdAt: new Date().toISOString() }
    mockCategories.push(category)
    return mockDelay(category)
  },

  update(categoryId: number, request: UpdateCategoryRequest): Promise<Category> {
    const name = request.name.trim()
    if (!name) return Promise.reject(new Error("Category name is required."))
    const category = mockCategories.find((c) => c.categoryId === categoryId)
    if (!category) return Promise.reject(new Error("Category not found."))
    category.name = name
    return mockDelay(category)
  },

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