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

import { redirect } from 'react-router'
import { parse } from 'cookie'

export async function loader({ request, context }: Route.LoaderArgs) {
  const cookies = parse(request.headers.get('Cookie') || '')
  const url = new URL(request.url)
  const loginUrl = new URL('/', url.origin)
  const authorizeUrl = new URL('/authorize', context.cloudflare.env.ISSUER_URL)
  authorizeUrl.search = url.search
  loginUrl.search = url.search

  if (!cookies?.SID) {
    throw redirect(loginUrl.toString())
  }

  if (!url.searchParams.has('client_id')) {
    throw redirect(context.cloudflare.env.APP_URL)
  }

  const r = await fetch(authorizeUrl.toString(), {
    method: 'GET',
    headers: new Headers([
      ['Content-Type', 'application/json'],
      ['Cookie', request.headers.get('Cookie') as string]
    ]),
    redirect: 'manual'
  })

  if (r.status === 302) {
    return new Response(null, {
      status: r.status,
      headers: r.headers
    })
  }

  // Deny authorization if user lacks scopes requested by client
  if (r.status === 403) {
    throw redirect(new URL('/deny', url.origin).toString())
  }

  throw redirect(loginUrl.toString())
}
