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

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

  // const res: any = await event.context.fetch(`models/c_order?$filter=${string.urlEncode('isSOTrx eq true AND (isActive eq true)')}&`+
  //     `$expand=c_bpartner_location_id,bill_location_id,m_inout&`+
  //     `$orderby=${string.urlEncode('c_order_id asc')}&`+
  //     `$top=10&$skip=0`, 'GET', token, null) // AND ExternalOrderId neq NULL
  const res: any = await event.context.fetch(`views/C_Order_NotFulfilled`, 'GET', token, null) // AND ExternalOrderId neq 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) {
      //@ts-ignore
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})