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

const profile = async (event: any, body: any, config: any) => {
  let data: any = {}
  const token = getCookie(event, 'token')

  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 {
      refreshTokenHelper(event)
      data = profile(event, body, config)
    } catch(error) {
      data = {
        //@ts-ignore
        status: error.status,
        //@ts-ignore
        message: error.message
      }
      forceLogoutHelper(event, data)
    }
  }

  return data
})