import type { MetadataRoute } from "next";
import { getPublicSiteUrl } from "@/lib/mail-urls";
import { getPublishedMarketingBlogPosts } from "@/lib/marketing-blog";
import { seoPages } from "@/lib/seo-pages";
import { SUPPORTED_LOCALES, getLocaleOption, type SupportedLocale } from "@/lib/i18n-config";
import { LOCALIZED_BLOG_SLUGS } from "@/lib/localized-blog-slugs";
import {
  getLocalizedPublicPath,
} from "@/lib/i18n-urls";

export const dynamic = "force-dynamic";

function absoluteUrl(path: string) {
  return new URL(path, getPublicSiteUrl()).toString();
}

const lastContentUpdate = new Date("2026-07-24T00:00:00+09:00");

function sitemapEntries(
  path: string,
  priority: number,
  changeFrequency: MetadataRoute.Sitemap[number]["changeFrequency"],
  lastModified = lastContentUpdate,
  locales: readonly SupportedLocale[] = SUPPORTED_LOCALES,
) {
  const languages = Object.fromEntries(
    locales.map((locale) => [
      getLocaleOption(locale).htmlLang,
      absoluteUrl(getLocalizedPublicPath(path, locale)),
    ]),
  );

  if (locales.length > 1) {
    languages["x-default"] = absoluteUrl(getLocalizedPublicPath(path, "ko"));
  }

  return locales.map((locale) => ({
    url: absoluteUrl(getLocalizedPublicPath(path, locale)),
    lastModified,
    changeFrequency,
    priority,
    alternates: { languages },
  }));
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const blogPosts = await getPublishedMarketingBlogPosts();
  const latestBlogUpdate = blogPosts.reduce(
    (latest, post) => Math.max(latest, new Date(post.updatedAt).getTime()),
    lastContentUpdate.getTime(),
  );
  const staticPages = [
    { path: "/", priority: 1, changeFrequency: "weekly" as const },
    { path: "/guide", priority: 0.9, changeFrequency: "monthly" as const },
    { path: "/domain-mail-check", priority: 0.95, changeFrequency: "weekly" as const },
    { path: "/partner", priority: 0.75, changeFrequency: "monthly" as const },
    {
      path: "/blog",
      priority: 0.9,
      changeFrequency: "daily" as const,
      lastModified: new Date(latestBlogUpdate),
    },
    { path: "/terms", priority: 0.35, changeFrequency: "yearly" as const },
    { path: "/privacy", priority: 0.35, changeFrequency: "yearly" as const },
    { path: "/account-deletion", priority: 0.3, changeFrequency: "yearly" as const },
  ];

  return [
    ...staticPages.flatMap((page) =>
      sitemapEntries(
        page.path,
        page.priority,
        page.changeFrequency,
        page.lastModified ?? lastContentUpdate,
      ),
    ),
    ...seoPages.flatMap((page) =>
      sitemapEntries(
        `/${page.slug}`,
        page.slug === "business-email" ? 0.95 : 0.85,
        "weekly",
      ),
    ),
    ...blogPosts.flatMap((post) =>
      sitemapEntries(
        `/blog/${post.slug}`,
        0.8,
        "weekly",
        new Date(post.updatedAt),
        LOCALIZED_BLOG_SLUGS.includes(post.slug as (typeof LOCALIZED_BLOG_SLUGS)[number])
          ? SUPPORTED_LOCALES
          : (["ko"] as const),
      ),
    ),
  ];
}
