import type { MetadataRoute } from "next";
import { prisma } from "@/lib/db";
import { TOOLS, TOOL_GROUPS } from "@/lib/tool-catalog";
import { getSetting } from "@/lib/settings";

// Sitemap reads runtime DB settings (site.url) and live blog posts —
// must be dynamic to reflect changes without rebuild.
export const dynamic = "force-dynamic";
export const revalidate = 0;

const STATIC_PAGES: {
  path: string;
  changeFrequency: MetadataRoute.Sitemap[number]["changeFrequency"];
  priority: number;
}[] = [
  { path: "/", changeFrequency: "daily", priority: 1.0 },
  { path: "/blog", changeFrequency: "daily", priority: 0.9 },
  { path: "/lien-he", changeFrequency: "yearly", priority: 0.3 },
  { path: "/dieu-khoan", changeFrequency: "yearly", priority: 0.2 },
  { path: "/bao-mat", changeFrequency: "yearly", priority: 0.2 },
  { path: "/cookie", changeFrequency: "yearly", priority: 0.2 },
  { path: "/mien-tru-trach-nhiem", changeFrequency: "yearly", priority: 0.2 },
];

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const SITE_URL = await getSetting("site.url");
  const now = new Date();

  const entries: MetadataRoute.Sitemap = STATIC_PAGES.map(
    ({ path, changeFrequency, priority }) => ({
      url: `${SITE_URL}${path}`,
      lastModified: now,
      changeFrequency,
      priority,
    })
  );

  // Group landing pages
  for (const g of TOOL_GROUPS) {
    entries.push({
      url: `${SITE_URL}/${g.slug}`,
      lastModified: now,
      changeFrequency: "weekly",
      priority: 0.8,
    });
  }

  // All 25 tool pages
  for (const t of TOOLS) {
    if (t.available === false) continue;
    entries.push({
      url: `${SITE_URL}/${t.slug}`,
      lastModified: now,
      changeFrequency: "weekly",
      priority: 0.7,
    });
  }

  // Published blog posts
  try {
    const posts = await prisma.blogPost.findMany({
      where: { publishedAt: { not: null } },
      select: { slug: true, updatedAt: true, publishedAt: true },
      orderBy: { publishedAt: "desc" },
      take: 1000,
    });
    for (const p of posts) {
      entries.push({
        url: `${SITE_URL}/blog/${p.slug}`,
        lastModified: p.updatedAt ?? p.publishedAt ?? now,
        changeFrequency: "monthly",
        priority: 0.6,
      });
    }
  } catch (err) {
    console.warn("[sitemap] blog query failed:", err);
  }

  return entries;
}
