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

const handleFilter = (filter: any) => {
  let newFilter: string = ''

  if((filter?.['value'] ?? '') !== '') {
    newFilter += ` AND ${filter?.['key'] ?? ''} ${filter?.['operator'] ?? ''} ${filter?.['value'] ?? ''} ` 
  } 

  return newFilter   
}

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

  let newFilter: string = ''
  let newFilters: any[] = [
    {key: 'M_Warehouse_ID', value: `${query?.warehouseId ?? ''}`, operator: ' eq '},
    {key: 'M_LocatorType_ID', value: `${query?.locatorTypeId ?? ''}`, operator: ' eq '},
    {key: 'X', value: `'${query?.x ?? ''}'`, operator: ' eq '},
    {key: 'Y', value: `'${query?.y ?? ''}'`, operator: ' eq '},
    {key: 'Z', value: `'${query?.z ?? ''}'`, operator: ' eq '}
  ] 
  for(let newFtr of newFilters) {
    if(newFtr['value'] !== '' && newFtr['value'] !== `''` && newFtr['value'] !== 'undefined' && newFtr['value'] !== undefined) {
      newFilter += handleFilter(newFtr) 
    } 
  }
  if(newFilter?.startsWith(' AND ')) {
    newFilter = newFilter.slice(5)
  }
  const res: any = await event.context.fetch(`models/m_locator?$filter=${string.urlEncode(newFilter)}&$orderby=${string.urlEncode('id desc')}`, '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) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})