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

import { redirect } from 'react-router'

import { userContext } from '@repo/auth/context'
import type { User } from '@repo/auth/auth'

const konvivaApi = 'https://lms.saladeaula.digital'

export async function loader({ context }: Route.LoaderArgs) {
  const user = context.get(userContext) as User
  const secretKey = context.cloudflare.env.KONVIVA_SECRET_KEY
  const token = await getToken(user.email, secretKey)

  const url = new URL('/action/acessoExterno', konvivaApi)
  url.search = new URLSearchParams(token).toString()

  return redirect(url.toString())
}

async function getToken(
  email: string,
  secretKey: string
): Promise<Record<string, string>> {
  const headers = new Headers({
    Authorization: `KONVIVA ${secretKey}`,
    'Content-Type': 'application/json'
  })
  const url = new URL(`/action/api/usuarios/token`, konvivaApi)
  url.search = new URLSearchParams({ login: email }).toString()

  const r = await fetch(url.toString(), { method: 'GET', headers })

  if (!r.ok) {
    throw new Error(await r.text())
  }

  return await r.json()
}
