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

const profile = async (event: any, body: any, config: any, authToken: any = null) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)

  const res: any = await event.context.fetch('models/ad_user/'+body.id, 'PUT', token, {
    name: body.name,
    eMail: body.email,
    value: body.value,
    description: body.description
  })
  if(res) {
    setCookie(event, 'user', res)
    data['user'] = res
  }

  return data
}

export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const body = await readBody(event)

  let data: any = {}

  try {
    data = profile(event, body, config)
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = profile(event, body, config, authToken)
    } catch(error) {
      data = {
        //@ts-ignore
        status: error.status || error.statusCode || 500,
        //@ts-ignore
        message: error.message || error.message || error.statusMessage
      }
      forceLogoutHelper(event, data)
    }
  }

  return data
})