import type { MetadataRoute } from "next";

import { DEFAULT_LOCALE, LOCALES } from "@/lib/locales";
import { href, indexableTargets } from "@/lib/routes";
import { absoluteUrl, BUILD_DATE } from "@/lib/site";

/**
 * Blueprint 12: every locale, with alternates. The 404 route is excluded by
 * `indexableTargets`, and the home page carries the highest priority because
 * it is the page with existing ranking equity.
 *
 * The alternates include x-default, pointing where the `<link>` tags in the
 * page head point. The two signals have to agree: a sitemap that named four
 * languages with no default, against a head that named a default, is exactly
 * the ambiguity that gets one language picked as a duplicate of another.
 */
export default function sitemap(): MetadataRoute.Sitemap {
  const lastModified = new Date(BUILD_DATE);

  return indexableTargets().flatMap((target) =>
    LOCALES.map((locale) => ({
      url: absoluteUrl(href(target, locale)),
      lastModified,
      changeFrequency: "monthly" as const,
      priority: target.key === "home" ? 1 : target.key === "nexys" ? 0.9 : 0.7,
      alternates: {
        languages: Object.fromEntries([
          ...LOCALES.map((other) => [other, absoluteUrl(href(target, other))]),
          ["x-default", absoluteUrl(href(target, DEFAULT_LOCALE))],
        ]),
      },
    })),
  );
}
