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

export interface SaveItemPriceRow {
  clientId: string
  itemId: string
  effectiveDate: string
  unitPrice: number
  remark?: string
}
export interface SaveItemPricesRequest { rows: SaveItemPriceRow[] }
export interface SaveItemPricesResponse { requested: number; saved: number; created: number; updated: number }
export interface ItemLookupResult { id: string; code: string; displayName: string; status?: string }

export function toKbxProblem(error: unknown): KbxProblem | null { return isKbxProblem(error) ? error : null }

export const itemPriceApi = {
  async resolveItemByCode(code: string) {
    try { return await kbxApi.request<ItemLookupResult>('lookup.items.resolveByCode', { path:{ code } }) }
    catch (error) { if (isKbxProblem(error) && error.type === 'not-found') return null; throw error }
  },
  save(request: SaveItemPricesRequest, idempotencyKey: string) {
    return kbxApi.request<SaveItemPricesResponse, SaveItemPricesRequest>('erp.itemPrices.bulkSave', { body:request, idempotencyKey })
  },
}
