// One typed client method per Brand endpoint, mirroring lib/api/uoms.ts.
// In-memory sample data (lib/api/mock-data.ts) — no backend API calls.
import { PagedResponse } from "@/types/common"
import { Brand, CreateBrandRequest, UpdateBrandRequest } from "@/types/master-data"
import { allocateBrandId, mockBrands, mockDelay } from "@/lib/api/mock-data"

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

export const brandsApi = {
  list(params: ListBrandsParams = {}): Promise<PagedResponse<Brand>> {
    const term = params.q?.trim().toLowerCase()
    const sortOrder = params.sortOrder ?? "asc"
    const filtered = mockBrands
      .filter((b) => !term || b.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: CreateBrandRequest): Promise<Brand> {
    const name = request.name.trim()
    if (!name) return Promise.reject(new Error("Brand name is required."))
    if (mockBrands.some((b) => b.name.toLowerCase() === name.toLowerCase())) {
      return Promise.reject(new Error(`Brand "${name}" already exists.`))
    }
    const brand: Brand = { brandId: allocateBrandId(), name, createdAt: new Date().toISOString() }
    mockBrands.push(brand)
    return mockDelay(brand)
  },

  update(brandId: number, request: UpdateBrandRequest): Promise<Brand> {
    const name = request.name.trim()
    if (!name) return Promise.reject(new Error("Brand name is required."))
    const brand = mockBrands.find((b) => b.brandId === brandId)
    if (!brand) return Promise.reject(new Error("Brand not found."))
    if (mockBrands.some((b) => b.brandId !== brandId && b.name.toLowerCase() === name.toLowerCase())) {
      return Promise.reject(new Error(`Brand "${name}" already exists.`))
    }
    brand.name = name
    return mockDelay(brand)
  },

  remove(brandId: number): Promise<void> {
    const index = mockBrands.findIndex((b) => b.brandId === brandId)
    if (index === -1) return Promise.reject(new Error("Brand not found."))
    mockBrands.splice(index, 1)
    return mockDelay(undefined)
  },
}
