import { kbxApi } from '../../../../http/generated/kbxApiClient'
import type { KbxBulkSelectionRequest } from '@kbx/contracts'
import type { OrderSearchRow } from './order-list.definition'
import type { KbxOrderLifecycleValue } from '../../../../registry/statusCatalog'

export interface OrderSearchFilter {
  from: string
  to: string
  channelId?: string | null
  status?: string | null
  exceptionOnly?: boolean
  keyword?: string
  page: number
  pageSize: number
}

export type OrderBulkFilter = Omit<OrderSearchFilter, 'page' | 'pageSize'>

export interface OrderSearchResponse {
  items: OrderSearchRow[]
  totalCount: number
  totalQty: number
  totalAmount: number
  counters: { all: number; new: number; readyToShip: number; exceptions: number }
}

export interface ShipOrdersResult { requested: number; accepted: number; rejected: number }

export interface OrderDetailResponse {
  orderId:string
  orderNo:string
  version:number
  status:KbxOrderLifecycleValue
  orderDate:string
  customerId:string
  warehouseId:string
  receiverName:string
  phone:string
  postalCode?:string
  address1:string
  address2?:string
  lines:Array<{id:string;clientId:string;itemId:string;itemCode:string;itemName:string;orderQty:number;unitPrice:number;amount:number;remark:string}>
}

export const orderApi = {
  search(filter: OrderSearchFilter) {
    return kbxApi.request<OrderSearchResponse>('oms.orders.search', { query: filter })
  },

  getDetail(orderId:string) {
    return kbxApi.request<OrderDetailResponse>('oms.orders.get', { path:{ id:orderId } })
  },

  ship(selection: KbxBulkSelectionRequest<OrderBulkFilter>) {
    return kbxApi.request<ShipOrdersResult, KbxBulkSelectionRequest<OrderBulkFilter>>('oms.orders.ship', {
      body: selection,
      idempotencyKey: crypto.randomUUID(),
    })
  },
}
