import { urlLocaleMatcherRegex } from '@akinon/next/utils';

/**
 * XML Sitemap Route
 *
 * This route serves XML sitemaps from an S3 bucket.
 *
 * Required environment variables:
 * - SITEMAP_S3_BUCKET_NAME: The name of the S3 bucket containing the sitemaps
 *   Example: "0fb534"
 *
 * If the environment variable is not set, the route will return a 503 Service Unavailable
 * response with a JSON error message.
 */

export const dynamic = 'force-dynamic';

export async function GET(request: Request, context: { params: Promise<{ node: string }> }) {
  const { node } = await context.params;
  const url = new URL(request.url);
  const matchedLocale = url.pathname.match(urlLocaleMatcherRegex);

  const s3BucketName = process.env.SITEMAP_S3_BUCKET_NAME;

  if (!s3BucketName) {
    return new Response(
      JSON.stringify({
        error: 'Configuration error',
        message: 'Please set the SITEMAP_S3_BUCKET_NAME environment variable'
      }),
      {
        status: 503,
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );
  }

  const sitemap = await fetch(
    `https://s3.eu-central-1.amazonaws.com/${s3BucketName}/sitemaps/sitemaps/sitemap-${node}.xml.gz`
  );

  if (!sitemap.ok) {
    return new Response(
      JSON.stringify({
        error: 'Sitemap not found',
        message: `Failed to fetch sitemap for node: ${node}`
      }),
      {
        status: 503,
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );
  }

  let sitemapContent = await sitemap.text();

  if (matchedLocale?.[0]) {
    const localeSuffix = matchedLocale[0];
    const domainRegex = /(?<=<loc>\s*)https?:\/\/[^/<\s]+/g;

    sitemapContent = sitemapContent.replace(domainRegex, `$&${localeSuffix}`);
  }

  return new Response(sitemapContent, {
    headers: {
      'Content-Type': 'application/xml'
    }
  });
}
