import type { JsonObject } from '../../../types/json.js'
import {
  failOpen91Order,
  listOpen91Orders,
  retryOpen91Order,
} from '../../platforms/ninetyone/order-service.js'

export async function getAdminNinetyoneOrders(query: JsonObject = {}) {
  return listOpen91Orders({
    page: Number(query.page || 1) || 1,
    pageSize: Number(query.pageSize || 20) || 20,
    status: query.status || 'pending_config',
  })
}

export async function retryAdminNinetyoneOrder(orderId: number | string) {
  const result = await retryOpen91Order(orderId)
  return {
    orderId: Number(result.order?.id || 0),
    orderNo: String(result.order?.platform_order_id || '').trim(),
    orderStatus: String(result.order?.order_status || '').trim(),
    orderItemCount: Array.isArray(result.orderItems) ? result.orderItems.length : 0,
    taskCount: Array.isArray(result.tasks) ? result.tasks.length : 0,
  }
}

export async function failAdminNinetyoneOrder(orderId: number | string, payload: JsonObject = {}) {
  const result = await failOpen91Order(orderId, payload.reason)
  return {
    orderId: Number(result.order?.id || 0),
    orderNo: String(result.order?.platform_order_id || '').trim(),
    orderStatus: String(result.order?.order_status || '').trim(),
    orderItemCount: Array.isArray(result.orderItems) ? result.orderItems.length : 0,
    taskCount: Array.isArray(result.tasks) ? result.tasks.length : 0,
  }
}
