import { createFileRoute } from '@tanstack/react-router'

const getApiOrigin = () => {
  return process.env.VITE_API_BASE_URL || process.env.API_URL || 'http://localhost:3000'
}

const proxyAuthRequest = async (request: Request, splat: string | undefined) => {
  const target = new URL(`/api/auth/${splat || ''}`, getApiOrigin())

  if (request.url.includes('?')) {
    target.search = new URL(request.url).search
  }

  const upstream = await fetch(target, {
    method: request.method,
    headers: request.headers,
    body: request.method === 'GET' || request.method === 'HEAD' ? undefined : await request.blob(),
    redirect: 'manual',
  })

  return new Response(upstream.body, {
    status: upstream.status,
    statusText: upstream.statusText,
    headers: upstream.headers,
  })
}

export const Route = createFileRoute('/api/auth/$')({
  server: {
    handlers: {
      GET: async ({ request, params }) => proxyAuthRequest(request, params._splat),
      POST: async ({ request, params }) => proxyAuthRequest(request, params._splat),
    },
  },
})
