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, 'organizationId')
  const id = getRouterParam(event, 'id')

  // const res: any = await event.context.fetch(`models/c_invoice/${id}`, 'GET', token, null)
  // const res: any = await fetchHelper(event, `models/a_asset?$filter=${string.urlEncode('isActive eq true OR isActive eq false')}&orderby=a_asset_${string.urlEncode('id desc')}`, 'GET', token, null)
  const res: any = await event.context.fetch(`models/ad_changelog?$filter=${string.urlEncode('AD_Table_ID eq 259 AND Record_ID eq ')}${id}`, 'GET', token, null)
  // const res: any = await event.context.fetch(`models/ad_changelog?$filter=AD_Table_ID eq 259 AND Record_ID eq 1000017`, 'GET', token, null)

  if(res) {
    data = res.records
  }

  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) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})