import { isKbxProblem, type KbxLookupProvider } from '@kbx/contracts'
import { kbxApi } from '../http/generated/kbxApiClient'

const lookupOperations = {
  customer: { search: 'lookup.customers.search', byId: 'lookup.customers.resolveById', byCode: 'lookup.customers.resolveByCode' },
  item: { search: 'lookup.items.search', byId: 'lookup.items.resolveById', byCode: 'lookup.items.resolveByCode' },
  warehouse: { search: 'lookup.warehouses.search', byId: 'lookup.warehouses.resolveById', byCode: 'lookup.warehouses.resolveByCode' },
} as const

type LookupEntity = keyof typeof lookupOperations

function provider(entity: LookupEntity): KbxLookupProvider<string> {
  const ops = lookupOperations[entity]
  return {
    search(request) {
      return kbxApi.request(ops.search, { query: request })
    },
    async resolveById(id) {
      try { return await kbxApi.request(ops.byId, { path: { id } }) }
      catch (error) { if (isKbxProblem(error) && error.type === 'not-found') return null; throw error }
    },
    async resolveByCode(code) {
      try { return await kbxApi.request(ops.byCode, { path: { code } }) }
      catch (error) { if (isKbxProblem(error) && error.type === 'not-found') return null; throw error }
    },
  } as KbxLookupProvider<string>
}

export const lookupRegistry = {
  customer: provider('customer'),
  item: provider('item'),
  warehouse: provider('warehouse'),
}
