import { NextResponse } from "next/server";
import {
  SITE_URL,
  SITEMAP_REVALIDATE_SECONDS,
} from "@/lib/sitemap/config";
import {
  countAcademiesPages,
  countBillboardsPages,
  countCoursesPages,
  countPostsPages,
  countProjectsPages,
  countUsersPages,
} 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 sitemapLoc(path: string) {
  return `  <sitemap>
    <loc>${SITE_URL}${path}</loc>
    <lastmod>${new Date().toISOString()}</lastmod>
  </sitemap>`;
}

/**
 * ایندکس اصلی — هر بار از API تعداد صفحات را می‌گیرد
 * تا پست/کاربر/پروژه/… جدید خودکار وارد sitemap شوند.
 */
export async function GET() {
  const [
    postsPages,
    usersPages,
    projectsPages,
    billboardsPages,
    coursesPages,
    academiesPages,
  ] = await Promise.all([
    countPostsPages().catch(() => 1),
    countUsersPages().catch(() => 1),
    countProjectsPages().catch(() => 1),
    countBillboardsPages().catch(() => 1),
    countCoursesPages().catch(() => 1),
    countAcademiesPages().catch(() => 1),
  ]);

  const parts: string[] = [
    sitemapLoc("/sitemaps/static.xml"),
    sitemapLoc("/sitemaps/filters.xml"),
  ];

  for (let i = 1; i <= postsPages; i++) {
    parts.push(sitemapLoc(`/sitemaps/posts/${i}.xml`));
  }
  for (let i = 1; i <= usersPages; i++) {
    parts.push(sitemapLoc(`/sitemaps/users/${i}.xml`));
  }
  for (let i = 1; i <= projectsPages; i++) {
    parts.push(sitemapLoc(`/sitemaps/projects/${i}.xml`));
  }
  for (let i = 1; i <= billboardsPages; i++) {
    parts.push(sitemapLoc(`/sitemaps/billboards/${i}.xml`));
  }
  for (let i = 1; i <= coursesPages; i++) {
    parts.push(sitemapLoc(`/sitemaps/courses/${i}.xml`));
  }
  for (let i = 1; i <= academiesPages; i++) {
    parts.push(sitemapLoc(`/sitemaps/academies/${i}.xml`));
  }

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${parts.join("\n")}
</sitemapindex>`;

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