import { NextResponse } from "next/server";
import {
  SITEMAP_REVALIDATE_SECONDS,
  type SitemapEntry,
} from "@/lib/sitemap/config";
import {
  buildAcademiesPage,
  buildBillboardsPage,
  buildCoursesPage,
  buildFilterEntries,
  buildPostsPage,
  buildProjectsPage,
  buildStaticEntries,
  buildUsersPage,
} from "@/lib/sitemap/builders";

export const dynamic = "force-dynamic";
// Must be a literal — Next.js cannot analyze imported revalidate values
export const revalidate = 3600;

function escapeXml(value: string): string {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;");
}

function toXml(entries: SitemapEntry[]): string {
  const urls = entries
    .map((item) => {
      const lastmod = item.lastModified
        ? new Date(item.lastModified).toISOString()
        : new Date().toISOString();
      return `  <url>
    <loc>${escapeXml(item.url)}</loc>
    <lastmod>${lastmod}</lastmod>
    <changefreq>${item.changeFrequency || "daily"}</changefreq>
    <priority>${(item.priority ?? 0.5).toFixed(1)}</priority>
  </url>`;
    })
    .join("\n");

  return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls}
</urlset>`;
}

function xmlResponse(entries: SitemapEntry[]) {
  return new NextResponse(toXml(entries), {
    headers: {
      "Content-Type": "application/xml; charset=utf-8",
      "Cache-Control": `public, s-maxage=${SITEMAP_REVALIDATE_SECONDS}, stale-while-revalidate`,
    },
  });
}

type RouteParams = {
  params: Promise<{ type: string; page?: string[] }>;
};

async function resolveEntries(
  type: string,
  pageRaw?: string
): Promise<SitemapEntry[]> {
  const page = Math.max(1, parseInt(String(pageRaw || "1"), 10) || 1);

  switch (type) {
    case "static":
      return buildStaticEntries();
    case "filters":
      return buildFilterEntries();
    case "posts":
      return buildPostsPage(page);
    case "users":
      return buildUsersPage(page);
    case "projects":
      return buildProjectsPage(page);
    case "billboards":
      return buildBillboardsPage(page);
    case "courses":
      return buildCoursesPage(page);
    case "academies":
      return buildAcademiesPage(page);
    default:
      return [];
  }
}

/** /sitemaps/static.xml | /sitemaps/filters.xml | /sitemaps/posts/1.xml */
export async function GET(_req: Request, { params }: RouteParams) {
  const { type, page } = await params;
  const normalizedType = type.replace(/\.xml$/i, "");
  const normalizedPage = page?.[0]?.replace(/\.xml$/i, "");

  const entries = await resolveEntries(normalizedType, normalizedPage);
  return xmlResponse(entries);
}
