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

export const dynamic = "force-dynamic";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const base = (process.env.APP_URL || "http://localhost:3000").replace(/\/$/, "");
  const [products, cats, cols, pages, posts] = await Promise.all([
    db.product.findMany({ where: { status: "PUBLISHED" }, select: { slug: true, updatedAt: true } }),
    db.category.findMany({ where: { visible: true }, select: { slug: true } }),
    db.collection.findMany({ where: { visible: true }, select: { slug: true } }),
    db.page.findMany({ where: { status: "PUBLISHED" }, select: { slug: true, updatedAt: true } }),
    db.editorialPost.findMany({ where: { status: "PUBLISHED" }, select: { slug: true } }),
  ]);
  return [
    { url: base, changeFrequency: "daily", priority: 1 },
    { url: `${base}/shop` }, { url: `${base}/journal` }, { url: `${base}/faq` }, { url: `${base}/contact` },
    ...cats.map((c) => ({ url: `${base}/collections/${c.slug}` })),
    ...cols.map((c) => ({ url: `${base}/collections/${c.slug}` })),
    ...products.map((p) => ({ url: `${base}/products/${p.slug}`, lastModified: p.updatedAt })),
    ...pages.map((p) => ({ url: `${base}/${p.slug}`, lastModified: p.updatedAt })),
    ...posts.map((p) => ({ url: `${base}/journal/${p.slug}` })),
  ];
}
