import { NextRequest, NextResponse } from "next/server";
import {
  buildStaticSitemap,
  buildShortsSitemap,
  buildLiveSitemap,
  buildCategoriesSitemap,
  buildVideoSitemapChunk,
  buildTagSitemapChunk,
  buildMasterSitemapIndex,
} from "@/lib/seoGenerator";
import { getCached, setCached } from "@/lib/memoryCache";

export const dynamic = "force-dynamic";

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  const { slug: rawSlug } = await params;
  const slug = rawSlug.replace(/\.xml$/, "").toLowerCase();

  const cacheKey = `sitemap_xml_${slug}`;
  const cachedXml = getCached<string>(cacheKey);
  if (cachedXml) {
    return new NextResponse(cachedXml, {
      headers: {
        "Content-Type": "application/xml; charset=utf-8",
        "Cache-Control": "public, max-age=86400, stale-while-revalidate=604800",
      },
    });
  }

  let xml = "";

  try {
    if (slug === "index" || slug === "sitemap" || slug === "index-1") {
      xml = buildMasterSitemapIndex(1);
    } else if (slug.startsWith("index-")) {
      const idx = parseInt(slug.replace("index-", ""), 10) || 1;
      xml = buildMasterSitemapIndex(idx);
    } else if (slug === "static") {
      xml = buildStaticSitemap();
    } else if (slug === "shorts" || slug === "sitemap-shorts") {
      xml = await buildShortsSitemap();
    } else if (slug === "live" || slug === "sitemap-live") {
      xml = buildLiveSitemap();
    } else if (slug === "categories") {
      xml = await buildCategoriesSitemap();
    } else if (slug.startsWith("videos-")) {
      const chunkIndex = parseInt(slug.replace("videos-", ""), 10) || 1;
      xml = await buildVideoSitemapChunk(chunkIndex);
    } else if (slug.startsWith("tags-")) {
      const chunkIndex = parseInt(slug.replace("tags-", ""), 10) || 1;
      xml = buildTagSitemapChunk(chunkIndex);
    } else {
      return new NextResponse("Sitemap not found", { status: 404 });
    }

    // Cache generated XML in memory (24h TTL)
    setCached(cacheKey, xml, 86400000);

    return new NextResponse(xml, {
      headers: {
        "Content-Type": "application/xml; charset=utf-8",
        "Cache-Control": "public, max-age=86400, stale-while-revalidate=604800",
      },
    });
  } catch (error: any) {
    console.error("Sitemap generation error for slug:", slug, error);
    return new NextResponse("Error generating sitemap", { status: 500 });
  }
}
