import type { MetadataRoute } from "next";
import { unstable_noStore as noStore } from "next/cache";

import { routing } from "@/i18n/routing";
import { getLocalizedPath } from "@/lib/locale";
import { getPublishedPortfolioProjects } from "@/lib/portfolio";

function getSiteUrl(): URL {
  return new URL(process.env.NEXT_PUBLIC_SITE_URL ?? "https://mohfarawati.de");
}

function toAbsoluteUrl(pathname: string): string {
  return new URL(pathname, getSiteUrl()).toString();
}

function buildLocalizedEntries(
  pathname: string,
  options?: Pick<MetadataRoute.Sitemap[number], "changeFrequency" | "priority" | "lastModified">,
): MetadataRoute.Sitemap {
  return routing.locales.map((locale) => ({
    url: toAbsoluteUrl(getLocalizedPath(locale, pathname)),
    lastModified: options?.lastModified,
    changeFrequency: options?.changeFrequency,
    priority: options?.priority,
  }));
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  noStore();

  let projects: Awaited<ReturnType<typeof getPublishedPortfolioProjects>> = [];

  try {
    projects = await getPublishedPortfolioProjects();
  } catch {
    projects = [];
  }

  const categories = Array.from(
    new Map(projects.map((project) => [project.category.slug, project.category])).values(),
  );

  return [
    ...buildLocalizedEntries("/", {
      changeFrequency: "weekly",
      priority: 1,
    }),
    ...buildLocalizedEntries("/about", {
      changeFrequency: "monthly",
      priority: 0.8,
    }),
    ...buildLocalizedEntries("/portfolio", {
      changeFrequency: "weekly",
      priority: 0.9,
    }),
    ...categories.flatMap((category) =>
      buildLocalizedEntries(`/portfolio/category/${category.slug}`, {
        changeFrequency: "weekly",
        priority: 0.8,
      }),
    ),
    ...buildLocalizedEntries("/contact", {
      changeFrequency: "monthly",
      priority: 0.7,
    }),
    ...projects.flatMap((project) =>
      buildLocalizedEntries(`/portfolio/${project.slug}`, {
        lastModified: project.publishedAt ?? undefined,
        changeFrequency: "monthly",
        priority: 0.8,
      }),
    ),
  ];
}
