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')
  let data: any[] = []

  try {
    const res: any[] | any = await fetchHelper(event, 'auth/language?client='+clientId, 'GET', token, null)
    if(res?.language) {
      data = res.language
    } else {
      if(Array.isArray(res) && res.length >= 1) {
        data = res
      }
      if(typeof res === 'object' && res !== null && !Array.isArray(res)) {
        data = [res]
      }
    }
  } catch(error: any) {
    data = [{AD_Language: 'en_US'}]
  }

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