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

// Union of the fields mapped by all consumers (sales/returns, sales/my-returns,
// dashboard card) — never the blob columns (DHL_Label_Base64, DPD_Label_Base64,
// trackingnoarray, marketplace_confirm_log); unbounded full-column m_inout list
// queries OOM-crashed the ERP on 2026-07-07. M_RMA_ID must stay in $select or
// its $expand is dropped by idempiere-rest.
const SELECT = 'DocumentNo,Description,DocStatus,MovementType,MovementDate,DateAcct,DateOrdered,Created,ProcessedOn,Processed,IsActive,IsApproved,IsSOTrx,IsPrinted,IsInTransit,IsInDispute,IsDropShip,IsAlternateReturnAddress,SendEMail,POReference,FreightAmt,ChargeAmt,NoPackages,Volume,Weight,DeliveryRule,FreightCostRule,DeliveryViaRule,PriorityRule,M_RMA_ID,C_DocType_ID,C_BPartner_ID,C_BPartner_Location_ID,C_Order_ID,AD_User_ID,AD_Org_ID,M_Warehouse_ID,SalesRep_ID,C_Project_ID,C_Campaign_ID'

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  const query = getQuery(event)

  // Opt-in line expansion: only callers that need the returned-article totals
  // (e.g. the dashboard "Letzte Retouren" card) pass ?withLines=1, so the
  // heavier payload is not forced on the my-returns list page. The product is
  // nested-expanded so the dashboard can show real product names.
  const expand = query?.withLines ? 'M_RMA_ID,m_inoutline($expand=m_product_id)' : 'M_RMA_ID'

  // Safety cap: ~460 returns exist today; the grids expect the full list, so the
  // cap only guards against unbounded growth.
  const res: any = await fetchHelper(event, `models/m_inout?$filter=startswith(MovementType,'C%2B')${string.urlEncode(" AND (isActive eq true OR isActive eq false)")}&$select=${SELECT}&$expand=${expand}&$orderby=${string.urlEncode('M_InOut_ID desc')}&$top=2000`, 'GET', token, null)
  if(res) {
    data = res
  }

  return data
}

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
})