import type { MetadataRoute } from "next";
import { siteUrl } from "@/lib/seo/site";
import { SEO_ROUTES, publicUrl } from "@/lib/seo/slugs";

function homepageAlternates(): MetadataRoute.Sitemap[number]["alternates"] {
  return {
    languages: {
      de: `${siteUrl}/de`,
      en: `${siteUrl}/en`,
      "x-default": `${siteUrl}/en`,
    },
  };
}

export default function sitemap(): MetadataRoute.Sitemap {
  const lastModified = new Date();
  const blogPostLastModified = new Date("2026-08-19");

  const entries: MetadataRoute.Sitemap = [
    {
      url: `${siteUrl}/de`,
      lastModified,
      changeFrequency: "weekly",
      priority: 1.0,
      alternates: homepageAlternates(),
    },
    {
      url: `${siteUrl}/en`,
      lastModified,
      changeFrequency: "weekly",
      priority: 1.0,
      alternates: homepageAlternates(),
    },
    {
      url: `${siteUrl}/de/blog`,
      lastModified,
      changeFrequency: "weekly",
      priority: 0.8,
      alternates: {
        languages: {
          de: `${siteUrl}/de/blog`,
          en: `${siteUrl}/en/blog`,
          "x-default": `${siteUrl}/en/blog`,
        },
      },
    },
    {
      url: `${siteUrl}/en/blog`,
      lastModified,
      changeFrequency: "weekly",
      priority: 0.8,
      alternates: {
        languages: {
          de: `${siteUrl}/de/blog`,
          en: `${siteUrl}/en/blog`,
          "x-default": `${siteUrl}/en/blog`,
        },
      },
    },
  ];

  for (const route of SEO_ROUTES) {
    const isBlogPost = route.key.startsWith("blog/");
    const languages = {
      de: publicUrl("de", route.key),
      en: publicUrl("en", route.key),
      "x-default": publicUrl("en", route.key),
    };
    const meta = {
      lastModified: isBlogPost ? blogPostLastModified : lastModified,
      changeFrequency: (isBlogPost ? "monthly" : "weekly") as MetadataRoute.Sitemap[number]["changeFrequency"],
      priority: isBlogPost ? 0.6 : 0.8,
      alternates: { languages },
    };
    entries.push({ url: publicUrl("de", route.key), ...meta });
    entries.push({ url: publicUrl("en", route.key), ...meta });
  }

  entries.push(
    {
      url: `${siteUrl}/terms`,
      lastModified,
      changeFrequency: "monthly",
      priority: 0.3,
    },
    {
      url: `${siteUrl}/privacy`,
      lastModified,
      changeFrequency: "monthly",
      priority: 0.3,
    },
    {
      url: `${siteUrl}/disclaimer`,
      lastModified,
      changeFrequency: "monthly",
      priority: 0.3,
    },
  );

  return entries;
}
