import { prisma } from "@/lib/prisma";
import { countriesData } from "@/app/data/countriesData";

/**
 * Native Next.js sitemap generation.
 * Replaces the legacy /sitemap.xml/route.js handler.
 * https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap
 */
export default async function sitemap() {
  const siteUrl =
    process.env.NEXT_PUBLIC_SITE_URL?.replace(/\/$/, "") ||
    "https://www.espotintl.com";

  // --- Static routes ---
  const staticRoutes = [
    { path: "", priority: 1.0, changeFrequency: "weekly" },
    { path: "/countries", priority: 0.8, changeFrequency: "weekly" },
    { path: "/resources", priority: 0.8, changeFrequency: "monthly" },
    { path: "/events", priority: 0.8, changeFrequency: "weekly" },
    { path: "/about", priority: 0.6, changeFrequency: "monthly" },
    { path: "/contact", priority: 0.6, changeFrequency: "monthly" },
    { path: "/services", priority: 0.7, changeFrequency: "monthly" },
    { path: "/tools", priority: 0.9, changeFrequency: "weekly" },
    { path: "/vision", priority: 0.5, changeFrequency: "monthly" },
    { path: "/appendix/privacy-policy", priority: 0.3, changeFrequency: "yearly" },
  ];

  // --- Country routes from static data ---
  const countryRoutes = countriesData
    .filter((c) => c?.slug)
    .map((c) => ({
      url: `${siteUrl}/countries/${c.slug}`,
      lastModified: new Date(),
      changeFrequency: "weekly",
      priority: 0.9,
    }));

  // --- Blog/resource routes from DB ---
  let blogRoutes = [];
  try {
    const blogs = await prisma.blog.findMany({
      where: { isPublished: true },
      select: { slug: true, updatedAt: true, createdAt: true },
      orderBy: { updatedAt: "desc" },
    });

    blogRoutes = blogs
      .filter((b) => b.slug)
      .map((post) => ({
        url: `${siteUrl}/resources/${post.slug}`,
        lastModified: post.updatedAt || post.createdAt || new Date(),
        changeFrequency: "monthly",
        priority: 0.7,
      }));
  } catch (err) {
    console.error("[sitemap] Failed to fetch blogs:", err.message);
  }

  // --- Event routes from DB ---
  let eventRoutes = [];
  try {
    const events = await prisma.event.findMany({
      where: { isPublished: true },
      select: { slug: true, date: true },
      orderBy: { date: "desc" },
    });

    eventRoutes = events
      .filter((e) => e.slug)
      .map((event) => ({
        url: `${siteUrl}/events/${event.slug}`,
        lastModified: event.date || new Date(),
        changeFrequency: "weekly",
        priority: 0.7,
      }));
  } catch (err) {
    console.error("[sitemap] Failed to fetch events:", err.message);
  }

  return [
    ...staticRoutes.map((route) => ({
      url: `${siteUrl}${route.path}`,
      lastModified: new Date(),
      changeFrequency: route.changeFrequency,
      priority: route.priority,
    })),
    ...countryRoutes,
    ...blogRoutes,
    ...eventRoutes,
  ];
}
