// One typed client method per warehouse/bin endpoint (docs/11-BACKEND-PHASE1.md §2.5,
// FR-MD-07/FR-WH-01). In-memory sample data (lib/api/mock-data.ts) — no backend API calls.
import { PagedResponse } from "@/types/common"
import { Bin, Warehouse } from "@/types/master-data"
import { allocateBinId, allocateWarehouseId, mockBins, mockDelay, mockWarehouses } from "@/lib/api/mock-data"

export interface CreateWarehouseRequest {
  code: string
  name: string
}

export interface CreateBinRequest {
  code: string
  binType?: string | null
}

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

  get(warehouseId: number): Promise<Warehouse> {
    const wh = mockWarehouses.find((w) => w.warehouseId === warehouseId)
    if (!wh) return Promise.reject(new Error(`Mock warehouse ${warehouseId} not found`))
    return mockDelay(wh)
  },

  create(request: CreateWarehouseRequest): Promise<Warehouse> {
    const code = request.code.trim()
    if (!code) return Promise.reject(new Error("Warehouse code is required."))
    if (mockWarehouses.some((w) => w.code.toLowerCase() === code.toLowerCase())) {
      return Promise.reject(Object.assign(new Error(`Warehouse code "${code}" already exists.`), { code: "SKU_DUPLICATE" }))
    }
    const warehouse: Warehouse = { warehouseId: allocateWarehouseId(), code, name: request.name.trim() }
    mockWarehouses.push(warehouse)
    return mockDelay(warehouse)
  },

  listBins(warehouseId: number): Promise<PagedResponse<Bin>> {
    const items = mockBins.filter((b) => b.warehouseId === warehouseId)
    return mockDelay({
      items,
      pagination: { page: 1, pageSize: 20, totalItems: items.length, totalPages: 1 },
    })
  },

  createBin(warehouseId: number, request: CreateBinRequest): Promise<Bin> {
    const code = request.code.trim()
    if (!code) return Promise.reject(new Error("Bin code is required."))
    if (mockBins.some((b) => b.warehouseId === warehouseId && b.code.toLowerCase() === code.toLowerCase())) {
      return Promise.reject(Object.assign(new Error(`Bin code "${code}" already exists in this warehouse.`), { code: "SKU_DUPLICATE" }))
    }
    const bin: Bin = { binId: allocateBinId(), warehouseId, code, binType: request.binType?.trim() || null }
    mockBins.push(bin)
    return mockDelay(bin)
  },
}
