import prisma from "@/server/db/prisma";

interface SitemapUrl {
  url: string;
  lastmod?: string;
  changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
  priority?: number;
}

export async function generateSitemap(): Promise<string> {
  const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "https://nitescape.com";
  const urls: SitemapUrl[] = [
    // Static pages
    { url: "/", changefreq: "daily", priority: 1.0 },
    { url: "/about", changefreq: "monthly", priority: 0.8 },
    { url: "/contact", changefreq: "monthly", priority: 0.8 },
  ];

  // Add projects
  const projects = await prisma.project.findMany({
    select: { id: true, updatedAt: true },
  });
  projects.forEach((project) => {
    urls.push({
      url: `/projects/${project.id}`,
      lastmod: project.updatedAt.toISOString(),
      changefreq: "weekly",
      priority: 0.7,
    });
  });

  // Add bold products
  const boldProducts = await prisma.bold.findMany({
    select: { id: true },
  });
  boldProducts.forEach((product) => {
    urls.push({
      url: `/bold/${product.id}`,
      changefreq: "weekly",
      priority: 0.7,
    });
  });

  // Add services
  const services = await prisma.service.findMany({
    select: { id: true },
  });
  services.forEach((service) => {
    urls.push({
      url: `/services/${service.id}`,
      changefreq: "monthly",
      priority: 0.6,
    });
  });

  // Generate XML
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  ${urls
    .map(
      (url) => `
  <url>
    <loc>${baseUrl}${url.url}</loc>
    ${url.lastmod ? `<lastmod>${url.lastmod}</lastmod>` : ""}
    ${url.changefreq ? `<changefreq>${url.changefreq}</changefreq>` : ""}
    ${url.priority ? `<priority>${url.priority}</priority>` : ""}
  </url>`,
    )
    .join("")}
</urlset>`;

  return xml;
}
