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

import { redirect } from 'react-router'

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

export async function loader({ request, context }: Route.ActionArgs) {
  const sessionStorage = createSessionStorage(context.cloudflare.env)
  const session = await sessionStorage.getSession(request.headers.get('cookie'))
  const returnTo = session.has('returnTo') ? session.get('returnTo') : '/'
  const requestId = context.get(requestIdContext)
  const user = session.get('user') as User | null

  if (user) {
    return redirect(returnTo)
  }

  try {
    const authenticator = createAuth(context.cloudflare.env)
    const user = await authenticator.authenticate('oidc', request)
    session.set('user', user)

    console.log(`[${requestId}] Redirecting the user to ${returnTo}`)

    // Redirect to the home page after successful login
    return redirect(returnTo, {
      headers: {
        'Set-Cookie': await sessionStorage.commitSession(session)
      }
    })
  } catch (error) {
    console.error(`[${requestId}]`, error)

    if (error instanceof Error) {
      return Response.json(
        { error: error.message },
        {
          status: 400,
          headers: {
            'Content-Type': 'application/json; utf-8'
          }
        }
      )
    }

    // Re-throw any other errors (including redirects)
    throw error
  }
}
