import { string } from 'alga-js'
import refreshTokenHelper from "../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../utils/errorHandlingHelper"
import fetchHelper from "../../utils/fetchHelper"

const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const query = getQuery(event)
  const orderSourceId = query.orderSourceId as string
  const days = parseInt(query.days as string) || 0

  if (!orderSourceId) {
    return { status: 400, message: 'orderSourceId is required', records: [] }
  }

  const now = new Date()
  const startDate = new Date(now)
  startDate.setDate(startDate.getDate() - days)
  const startDateStr = startDate.toISOString().split('T')[0]

  console.log(`[shipping-confirmations] orderSourceId=${orderSourceId}, days=${days}, startDate=${startDateStr}`)

  const filter = string.urlEncode(
    `C_OrderSource_ID eq ${orderSourceId} AND DocStatus eq 'CO' AND isSOTrx eq true AND DateOrdered ge '${startDateStr}'`
  )

  const expand = string.urlEncode(
    'C_Orderline($expand=M_Product_ID),M_InOut($expand=M_Shipper_ID)'
  )

  const res: any = await fetchHelper(
    event,
    `models/c_order?$filter=${filter}&$expand=${expand}&$orderby=${string.urlEncode('c_order_id desc')}&$top=500`,
    'GET',
    token,
    null
  )

  if (!res?.records) {
    return { records: [] }
  }

  const shippedOrders = []
  for (const order of res.records) {
    const inouts = order.M_InOut || order.m_inout || []
    const shippedInouts = inouts.filter((inout: any) => !!(inout.TrackingNo))

    if (shippedInouts.length === 0) continue

    // Get external order id - try ExternalOrderId, then POReference, then Description
    const externalOrderId = order.ExternalOrderId || order.POReference || order.Description || ''

    const orderLines = order.C_Orderline || order.c_orderline || []

    shippedOrders.push({
      orderId: order.id,
      documentNo: order.DocumentNo,
      externalOrderId: externalOrderId,
      dateOrdered: order.DateOrdered,
      partnerName: order.C_BPartner_ID?.identifier || '',
      orderLines: orderLines.map((line: any) => ({
        id: line.id,
        lineNo: line.Line,
        productName: line.M_Product_ID?.Name || line.M_Product_ID?.identifier || '',
        productValue: line.M_Product_ID?.Value || '',
        qty: line.QtyOrdered || line.QtyEntered || 0,
        qtyDelivered: line.QtyDelivered || 0,
      })),
      shipments: shippedInouts.map((inout: any) => ({
        id: inout.id,
        documentNo: inout.DocumentNo,
        trackingNo: inout.TrackingNo || '',
        shippingDate: inout.shipping_date || inout.MovementDate || '',
        shipperName: inout.M_Shipper_ID?.Name || inout.M_Shipper_ID?.identifier || '',
        shippingServiceName: inout.shipping_service_name || '',
      })),
    })
  }

  console.log(`[shipping-confirmations] Found ${shippedOrders.length} shipped orders out of ${res.records.length} total`)
  return { records: shippedOrders }
}

export default defineEventHandler(async (event) => {
  let data: any = {}

  try {
    data = await handleFunc(event)
  } catch (err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch (error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})
