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 number = getRouterParam(event, 'number')

  //const res: any = await fetchHelper(event, `models/c_bpartner_location?$select=C_BPartner_ID,phone,phone2,isdn&$filter=${string.urlEncode('contains(phone,"'+number+'") OR contains(phone2,"'+number+'")')}`, 'GET', token, null)
  let res: any = await fetchHelper(event, `models/c_bpartner_location?$select=C_BPartner_ID,phone,phone2,isdn&$filter=${string.urlEncode("phone eq '"+number+"' OR phone2 eq '"+number+"'")}`, 'GET', token, null)
  if((res?.records.length ?? 0) == 0) {
    res = await fetchHelper(event, `models/ad_user?$select=C_BPartner_ID,phone,phone2,fax&$filter=${string.urlEncode("phone eq '"+number+"' OR phone2 eq '"+number+"'")}`, '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: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})