import type { MetadataRoute } from "next";
import { db } from "@/lib/db";

export const revalidate = 3600;

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const base = process.env.NEXT_PUBLIC_SITE_URL || "https://ahe-services.example.com";
  const now = new Date();

  const staticRoutes = [
    "", "about", "services", "projects", "before-after", "industries", "blog", "faq", "contact", "privacy-policy", "terms",
  ].map((p) => ({
    url: `${base}/${p}`,
    lastModified: now,
    changeFrequency: "weekly" as const,
    priority: p === "" ? 1 : 0.8,
  }));

  const services = await db.service.findMany({ where: { isEnabled: true }, select: { slug: true, updatedAt: true } });
  const projects = await db.project.findMany({ where: { isEnabled: true }, select: { slug: true, updatedAt: true } });
  const posts = await db.blogPost.findMany({ where: { isPublished: true }, select: { slug: true, updatedAt: true } });

  const serviceRoutes = services.map((s) => ({ url: `${base}/services/${s.slug}`, lastModified: s.updatedAt, changeFrequency: "monthly" as const, priority: 0.7 }));
  const projectRoutes = projects.map((p) => ({ url: `${base}/projects/${p.slug}`, lastModified: p.updatedAt, changeFrequency: "monthly" as const, priority: 0.6 }));
  const postRoutes = posts.map((p) => ({ url: `${base}/blog/${p.slug}`, lastModified: p.updatedAt, changeFrequency: "monthly" as const, priority: 0.6 }));

  return [...staticRoutes, ...serviceRoutes, ...projectRoutes, ...postRoutes];
}
