import { string } from 'alga-js'
import refreshTokenHelper from "../../../utils/refreshTokenHelper"
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 query = getQuery(event)
  const organizationId = query?.org ?? getCookie(event, 'logship_organization_id')
  const isCustomer = query?.customer || ''
  const isVendor = query?.vendor || ''

  let filter = `isActive eq true AND AD_Org_ID eq ${organizationId}`
  if(isCustomer !== '') {
    filter = `${filter} AND IsCustomer eq ${isCustomer}`
  }
  if(isVendor !== '') {
    filter = `${filter} AND IsVendor eq ${isVendor}`
  }

  const res: any = await fetchHelper(event, `models/c_bpartner?$filter=${string.urlEncode(filter)}&$orderby=${string.urlEncode('c_bpartner_id desc')}`, 'GET', token, null)
  if((res?.records?.length ?? 0) >= 1) {
    data = res
  } else {
    const res2: any = await fetchHelper(event, `models/c_bpartner?$filter=${string.urlEncode('isActive eq true')}&$orderby=${string.urlEncode('c_bpartner_id desc')}`, 'GET', token, null)
    if(res2) {
      data = res2
    }
  }

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