/**
 * Runtime proxy for /sitemap.xml → the FastAPI backend's generated sitemap.
 *
 * Like the /api/* proxy, this reads FASTAPI_URL at request time rather than
 * baking the backend host into the build, so one image works in every
 * environment. robots.ts points crawlers here.
 */

import { NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

function backendOrigin(): string {
  const base = process.env.FASTAPI_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api';
  return base.replace(/\/api$/, '');
}

export async function GET() {
  let upstream: Response;
  try {
    upstream = await fetch(`${backendOrigin()}/sitemap.xml`, { cache: 'no-store' });
  } catch {
    return new NextResponse('Sitemap temporarily unavailable', { status: 502 });
  }

  const body = await upstream.text();
  return new NextResponse(body, {
    status: upstream.status,
    headers: { 'content-type': upstream.headers.get('content-type') || 'application/xml' },
  });
}
