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

  try {
    const res: any[] | any = await fetchHelper(event, 'auth/roles?client=' + clientId, 'GET', token, null)
    if (res?.roles) {
      data = res.roles
    } else {
      if (res?.length >= 1) {
        data = res
      }
    }
  } catch (error: any) {
    const res: any[] | any = await fetchHelper(event, 'auth/roles?client=' + clientId, 'GET', token, null)
    if (res?.roles) {
      data = res.roles
    } 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
})