import { string } from 'alga-js'
import refreshTokenHelper from "../../utils/refreshTokenHelper"
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 body = await readBody(event)
  const orderIds: number[] = body.orderIds || []

  if (orderIds.length === 0) return {}

  const idsFilter = orderIds.map((id: number) => `C_Order_ID eq ${id}`).join(' OR ')
  const res: any = await fetchHelper(event,
    `models/c_orderline?$filter=${string.urlEncode(idsFilter)}&$expand=${string.urlEncode('M_Product_ID($select=Name,SKU,UPC,mpn,Value,Strapi_Product_documentId,ASIN,QtyOnHand)')}&$select=C_Order_ID,M_Product_ID,QtyEntered,PriceEntered,Line&$orderby=Line asc&$top=9999`,
    'GET', token, null
  )

  const linesByOrder: Record<number, any[]> = {}
  if (res?.records) {
    for (const line of res.records) {
      const orderId = line.C_Order_ID?.id || line.C_Order_ID
      if (!linesByOrder[orderId]) linesByOrder[orderId] = []
      linesByOrder[orderId].push({
        id: line.id,
        line: line.Line,
        productName: line.M_Product_ID?.Name || line.M_Product_ID?.identifier || '',
        sku: line.M_Product_ID?.SKU || '',
        upc: line.M_Product_ID?.UPC || '',
        asin: line.M_Product_ID?.ASIN || '',
        mpn: line.M_Product_ID?.mpn || '',
        value: line.M_Product_ID?.Value || '',
        strapiProductId: line.M_Product_ID?.Strapi_Product_documentId || '',
        qty: line.QtyEntered || 0,
        price: line.PriceEntered || 0,
        productId: line.M_Product_ID?.id || '',
        qtyOnHand: line.M_Product_ID?.QtyOnHand ?? 0,
      })
    }
  }

  return linesByOrder
}

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

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

  return data
})
