import type { Route } from './+types/verify'

import { redirect } from 'react-router'

import { userContext } from '@repo/auth/context'
import { createSessionStorage } from '@repo/auth/session'
import { HttpMethod, request as req } from '@repo/util/request'

export async function loader({ params, request, context }: Route.LoaderArgs) {
  const { code } = params
  const sessionStorage = createSessionStorage(context.cloudflare.env)
  const session = await sessionStorage.getSession(request.headers.get('cookie'))
  const user = context.get(userContext)

  const r = await req({
    url: `/users/${user.sub}/emails/${code}/verify`,
    method: HttpMethod.POST,
    request,
    context
  })

  if (r.ok) {
    session.flash('success', 'Seu email foi verificado.')
  } else {
    session.flash('info', 'O email já está verificado.')
  }

  return redirect('/settings/emails', {
    headers: new Headers({
      'Set-Cookie': await sessionStorage.commitSession(session)
    })
  })
}
