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

import { redirect } from 'react-router'
import type { OAuth2Strategy } from 'remix-auth-oauth2'

import { createAuth, type User } from '@repo/auth/auth'
import { createSessionStorage } from '@repo/auth/session'

export async function loader({ request, context }: Route.LoaderArgs) {
  const authenticator = createAuth(context.cloudflare.env)
  const sessionStorage = createSessionStorage(context.cloudflare.env)
  const session = await sessionStorage.getSession(request.headers.get('cookie'))
  const user = session.get('user') as User
  const strategy = authenticator.get<OAuth2Strategy<User>>('oidc')

  if (user?.accessToken && strategy) {
    await strategy.revokeToken(user.accessToken)
  }

  return redirect('/login', {
    headers: { 'Set-Cookie': await sessionStorage.destroySession(session) }
  })
}
