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

const handleFunc = async (event: any) => {
  let data: any = {}
  const config = useRuntimeConfig()
  const token = getCookie(event, 'token')
  const organizationId = getCookie(event, 'organizationId')
  const query = getQuery(event)

  const res: any = await event.context.fetch(`windows`, '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 {
      refreshTokenHelper(event)
      data = await handleFunc(event)
    } catch(error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})