export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const body = await readBody(event)
  let user: any = {}

  if(event.context.auth.user) {
    user = event.context.auth.user
  } else {
    const resToken: any = await $fetch(config.api.url+'/authenticate', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer '+event.context.auth.token
      },
      body: {
        password: body.password,
        rememberMe: body.remember,
        username: body.email
      }
    })
    if(resToken.id_token) {
      await useStorage().setItem<string>('token', resToken.id_token)

      const resUser: any = await $fetch(config.api.url+'/account', {
        headers: {
          'Authorization': 'Bearer '+resToken.id_token
        }
      })
      if(resUser?.id) {
        await useStorage().setItem<any>('user', resUser)
        user = resUser
      } else {
        user = null
      }
    }
  }

  return user
})