import laravelHelper from "../../../utils/laravelHelper"

// Manual "import this one Amazon order now" — proxies to the Laravel middleware,
// which owns the actual Amazon → iDempiere order-creation pipeline (same one the
// scheduled sync uses). No iDempiere token needed here: Laravel authenticates to
// iDempiere itself with its own service token.
export default defineEventHandler(async (event) => {
  const body: any = await readBody(event)
  const { orderSourceId, amazonOrderId, docTypeTargetId, deliveryRule, invoiceRule, priceListAdditions } = body || {}

  if (!orderSourceId || !amazonOrderId) {
    return { status: 400, message: 'orderSourceId and amazonOrderId are required' }
  }

  try {
    const res: any = await laravelHelper(event, 'sales/orders/import-amazon-order', 'POST', {
      orderSourceId, amazonOrderId, docTypeTargetId, deliveryRule, invoiceRule, priceListAdditions
    })
    // Preserve every field on failure too (errorType/productId/suggestedPrice/etc.) -
    // the reconciliation page's "add to price list & reimport" action needs them.
    return { ...res, status: res?.success ? 200 : 400 }
  } catch (err: any) {
    return { status: err?.status || 500, message: err?.data?.message || err?.message || 'Import failed' }
  }
})
