import type { MetadataRoute } from "next";
import { prisma } from "@/lib/prisma";
import { collections } from "@/lib/collections";
import { locales, type Locale } from "@/lib/i18n/config";
import { absoluteUrl } from "@/lib/utils";

export const dynamic = "force-dynamic";

const staticPaths = [
  { path: "", priority: 1 },
  { path: "/shop", priority: 0.9 },
  { path: "/collections", priority: 0.8 },
  { path: "/journal", priority: 0.7 },
  { path: "/story", priority: 0.7 },
  { path: "/contact", priority: 0.6 },
  { path: "/faq", priority: 0.5 },
  { path: "/shipping", priority: 0.4 },
  { path: "/care", priority: 0.4 },
  { path: "/privacy", priority: 0.3 },
  { path: "/terms", priority: 0.3 },
  { path: "/legal", priority: 0.3 },
  { path: "/newsletter", priority: 0.4 },
];

function languageAlternates(path: string) {
  return Object.fromEntries(locales.map((locale) => [locale, absoluteUrl(`/${locale}${path}`)]));
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const [products, articles] = await Promise.all([
    prisma.product.findMany({ where: { isPublished: true }, select: { slug: true, updatedAt: true } }),
    prisma.journalArticle.findMany({ where: { isPublished: true }, select: { slug: true, publishedAt: true } }),
  ]);

  const entries: MetadataRoute.Sitemap = [];

  for (const locale of locales as readonly Locale[]) {
    for (const item of staticPaths) {
      entries.push({
        url: absoluteUrl(`/${locale}${item.path}`),
        lastModified: new Date(),
        changeFrequency: item.path === "" ? "daily" : "weekly",
        priority: item.priority,
        alternates: { languages: languageAlternates(item.path) },
      });
    }

    for (const collection of collections) {
      entries.push({
        url: absoluteUrl(`/${locale}/collections/${collection.slug}`),
        lastModified: new Date(),
        changeFrequency: "weekly",
        priority: 0.7,
        alternates: { languages: languageAlternates(`/collections/${collection.slug}`) },
      });
    }

    for (const product of products) {
      entries.push({
        url: absoluteUrl(`/${locale}/product/${product.slug}`),
        lastModified: product.updatedAt,
        changeFrequency: "weekly",
        priority: 0.8,
        alternates: { languages: languageAlternates(`/product/${product.slug}`) },
      });
    }

    for (const article of articles) {
      entries.push({
        url: absoluteUrl(`/${locale}/journal/${article.slug}`),
        lastModified: article.publishedAt,
        changeFrequency: "monthly",
        priority: 0.6,
        alternates: { languages: languageAlternates(`/journal/${article.slug}`) },
      });
    }
  }

  return entries;
}
