import type { MetadataRoute } from "next";
import { getEvents } from "@/lib/api/events";

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000";

/**
 * FR-125: auto-generated sitemap. Built from `GET /events` (Published/Ongoing
 * only, same as the public listing) — Finished events are reachable at
 * `/events/{slug}` but intentionally omitted here, same simplification most
 * sitemaps make for archived/past content (lower priority for search
 * engines to (re)discover, not a broken link).
 */
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const staticRoutes: MetadataRoute.Sitemap = [
    { url: SITE_URL, changeFrequency: "daily", priority: 1 },
    { url: `${SITE_URL}/events`, changeFrequency: "hourly", priority: 0.9 },
    { url: `${SITE_URL}/faq`, changeFrequency: "monthly", priority: 0.3 },
    { url: `${SITE_URL}/terms`, changeFrequency: "yearly", priority: 0.1 },
    { url: `${SITE_URL}/privacy`, changeFrequency: "yearly", priority: 0.1 },
  ];

  const eventRoutes: MetadataRoute.Sitemap = [];
  let page = 1;
  let lastPage = 1;

  do {
    const res = await getEvents({ page });
    for (const event of res.data) {
      eventRoutes.push({
        url: `${SITE_URL}/events/${event.slug}`,
        lastModified: event.updated_at,
        changeFrequency: "weekly",
        priority: 0.7,
      });
    }
    lastPage = res.meta.last_page;
    page += 1;
  } while (page <= lastPage);

  return [...staticRoutes, ...eventRoutes];
}
