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 query = getQuery(event)

  let limit: number = query?.limit ?? 100
  let offset: number = query?.offset ?? 0

  const res: any = await event.context.fetch(`models/c_order?$select=C_Order_ID&$filter=${string.urlEncode('isSOTrx eq true AND isActive eq true')}&$expand=m_inout($select=M_Inout_ID)&$orderby=${string.urlEncode('c_order_id desc')}&$top=${limit}&$skip=${offset}`, '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) {
      //@ts-ignore
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})