import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import fetchHelper from '../../../utils/fetchHelper'

const getRoleData = async (event: any, roleId: string, authToken: any = null) => {
  const config = useRuntimeConfig()
  const token = authToken ?? getCookie(event, 'logship_it')

  const resRole: any = await fetchHelper(event, 'models/ad_role/'+roleId, 'GET', token, null)

  // Log the response to see its structure
  console.log('Role data from API:', JSON.stringify(resRole, null, 2))

  return resRole
}

export default defineEventHandler(async (event: any) => {
  const id = getRouterParam(event, 'id')
  let data: any = {}

  try {
    data = await getRoleData(event, id)
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await getRoleData(event, id, authToken)
    } catch(error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})
