import type { MetadataRoute } from "next";
import { siteUrl } from "@/lib/api";
import type { ArticleCard, ServiceCard } from "@/lib/types";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const base = siteUrl();
  const paths = ["", "/about", "/services", "/domains", "/innovation-finance", "/experience", "/insights", "/collaborate", "/contact", "/request"];
  const entries: MetadataRoute.Sitemap = paths.map((path) => ({ url: `${base}${path}`, changeFrequency: "weekly" }));

  try {
    const [services, articles] = await Promise.all([
      fetch(`${process.env.NEXT_PUBLIC_API_URL ?? "http://127.0.0.1:8000"}/api/v1/services`, { cache: "no-store" }).then((response) => response.json()) as Promise<{ services: ServiceCard[] }>,
      fetch(`${process.env.NEXT_PUBLIC_API_URL ?? "http://127.0.0.1:8000"}/api/v1/articles`, { cache: "no-store" }).then((response) => response.json()) as Promise<{ articles: ArticleCard[] }>,
    ]);
    services.services.forEach((service) => entries.push({ url: `${base}/services/${service.slug}`, changeFrequency: "monthly" }));
    articles.articles.forEach((article) => entries.push({ url: `${base}/insights/${article.slug}`, changeFrequency: "monthly" }));
  } catch {
    return entries;
  }

  return entries;
}
