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"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  //const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  //const organizationId = getCookie(event, 'organizationId')
  const trackingNo = getRouterParam(event, 'number')

  const newFilter = string.urlEncode(`(isActive eq true OR isActive eq false) AND contains(TrackingNo,'${trackingNo}')`)
  const res: any = await fetchHelper(event, `models/m_inout?$filter=${newFilter}&$expand=m_inoutline($expand=m_product_id),C_Order_ID,AD_User_ID,C_BPartner_Location_ID,M_Shipper_ID&$orderby=${string.urlEncode('id desc')}`, 'GET', token, null)
  if(res) {
    data = res
  }

  return data
}

export default defineEventHandler(async (event: any) => {
  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
})