import type { MetadataRoute } from "next";
import { apiUrl } from "@/lib/api-base";

const siteUrl =
  process.env.NEXT_PUBLIC_SITE_URL || "https://belgianbitcoinembassy.org";

async function fetchJson<T>(path: string): Promise<T | null> {
  try {
    const res = await fetch(apiUrl(path), { next: { revalidate: 3600 } });
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const staticRoutes: MetadataRoute.Sitemap = [
    { url: siteUrl, lastModified: new Date(), changeFrequency: "weekly", priority: 1.0 },
    { url: `${siteUrl}/blog`, lastModified: new Date(), changeFrequency: "daily", priority: 0.9 },
    { url: `${siteUrl}/events`, lastModified: new Date(), changeFrequency: "weekly", priority: 0.9 },
    { url: `${siteUrl}/community`, lastModified: new Date(), changeFrequency: "monthly", priority: 0.7 },
    { url: `${siteUrl}/contact`, lastModified: new Date(), changeFrequency: "monthly", priority: 0.5 },
    { url: `${siteUrl}/faq`, lastModified: new Date(), changeFrequency: "monthly", priority: 0.6 },
    { url: `${siteUrl}/privacy`, lastModified: new Date(), changeFrequency: "yearly", priority: 0.3 },
    { url: `${siteUrl}/terms`, lastModified: new Date(), changeFrequency: "yearly", priority: 0.3 },
  ];

  const blogRoutes: MetadataRoute.Sitemap = [];
  const postsData = await fetchJson<{ posts: any[]; total: number }>("/posts?limit=500");
  if (postsData?.posts) {
    for (const post of postsData.posts) {
      blogRoutes.push({
        url: `${siteUrl}/blog/${post.slug}`,
        lastModified: post.updatedAt || post.publishedAt || post.createdAt,
        changeFrequency: "weekly",
        priority: 0.8,
      });
    }
  }

  const eventRoutes: MetadataRoute.Sitemap = [];
  const meetups = await fetchJson<any[]>("/meetups");
  if (Array.isArray(meetups)) {
    for (const meetup of meetups) {
      eventRoutes.push({
        url: `${siteUrl}/events/${meetup.id}`,
        lastModified: meetup.updatedAt || meetup.createdAt,
        changeFrequency: "weekly",
        priority: 0.7,
      });
    }
  }

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