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

const handleFunc = async (event: any, authToken: any = null) => {
  const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  const clientId = getRouterParam(event, 'client')
  const roleId = getRouterParam(event, 'role')
  const organizationId = getRouterParam(event, 'organization')
  let data: any[] = []

  try {
    const res: any = await fetchHelper(event, `models/m_warehouse?$filter=${string.urlEncode('AD_Client_ID eq '+clientId+' AND AD_Role_ID eq '+roleId+' AND AD_Org_ID eq '+organizationId)}`, 'GET', token, null)
    if(res?.records) {
      data = res.records.map((i: any) => {
        i.name = i.Name || ''
        return i
      })
    } else {
      data = res
    }
  } catch(error: any) {
    const res: any[] | any = await fetchHelper(event, `auth/warehouses?client=${clientId}&role=${roleId}&organization=${organizationId}`, 'GET', token, null)
    if(res?.warehouses) {
      data = res.warehouses
    } else {
      if(res?.length >= 1) {
        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) {
      return [
        err,
        error,
        data
      ]
    }
  }

  return data
})