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

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

export const loader = proxy
export const action = proxy

async function proxy({
  request,
  context
}: Route.ActionArgs): Promise<Response> {
  const pathname = new URL(request.url).pathname.replace(/^\/api\//, '')
  const user = context.get(userContext) as User
  const url = new URL(pathname, context.cloudflare.env.API_URL)
  const headers = new Headers(request.headers)

  headers.set('Authorization', `Bearer ${user.accessToken}`)

  const response = await fetch(url.toString(), {
    method: request.method,
    headers,
    ...(['GET', 'HEAD'].includes(request.method)
      ? {}
      : { body: await request.text() })
  })

  const contentType = response.headers.get('content-type') || ''
  const body =
    contentType.includes('application/json') || contentType.startsWith('text/')
      ? await response.text()
      : await response.arrayBuffer()

  return new Response(body ? body : null, {
    status: response.status,
    headers: response.headers
  })
}
