import { countrySlug } from "./countrySlug";
import { expatStories } from "./expatContent";

export const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "https://send.mn";

export type UrlEntry = {
  loc: string;
  lastmod?: string;
  changefreq?:
    | "always"
    | "hourly"
    | "daily"
    | "weekly"
    | "monthly"
    | "yearly"
    | "never";
  priority?: number; // 0.0–1.0
};

type WebflowItem = { fieldData?: { slug?: string; date?: string } };

async function getBlogRoutes(): Promise<UrlEntry[]> {
  const blogSlugs = new Map<string, string | undefined>();

  try {
    const [enRes, mnRes] = await Promise.all([
      fetch(`${SITE_URL}/api/webflowEn`, {
        headers: { Accept: "application/json" },
      }),
      fetch(`${SITE_URL}/api/webflow`, {
        headers: { Accept: "application/json" },
      }),
    ]);
    const [enItems, mnItems]: [WebflowItem[], WebflowItem[]] =
      await Promise.all([
        enRes.ok ? enRes.json() : [],
        mnRes.ok ? mnRes.json() : [],
      ]);

    for (const item of [...enItems, ...mnItems]) {
      const slug = item?.fieldData?.slug;
      if (slug && !blogSlugs.has(slug)) {
        blogSlugs.set(slug, item?.fieldData?.date);
      }
    }
  } catch {
    /* no-op in sitemap */
  }

  return Array.from(blogSlugs.entries()).map(([slug, date]) => ({
    loc: `${SITE_URL}/blog/${slug}`,
    lastmod: date?.slice(0, 10),
    changefreq: "weekly",
    priority: 0.6,
  }));
}

async function getCountryRoutes(): Promise<UrlEntry[]> {
  type CountryListItem = { countryCode: string };
  let countryCodes: string[] = [];

  try {
    const r = await fetch(`${SITE_URL}/api/country`, {
      headers: { Accept: "application/json" },
    });
    const data = r.ok ? await r.json() : null;
    const list: CountryListItem[] = data?.Data?.countries ?? [];
    countryCodes = Array.from(
      new Set(
        list
          .map((c) => c.countryCode?.toLowerCase())
          .filter((code): code is string => Boolean(code))
      )
    );
  } catch {
    /* no-op in sitemap */
  }

  return countryCodes
    .map((code) => countrySlug(code))
    .filter((slug): slug is string => Boolean(slug))
    .map((slug) => ({
      loc: `${SITE_URL}/countries/${slug}`,
      changefreq: "weekly",
      priority: 0.6,
    }));
}

export async function getSitemapEntries(): Promise<UrlEntry[]> {
  const staticRoutes: UrlEntry[] = [
    {
      loc: `${SITE_URL}/`,
      priority: 1.0,
      changefreq: "daily",
      lastmod: new Date().toISOString().slice(0, 10),
    },
    { loc: `${SITE_URL}/about`, priority: 0.6 },
    { loc: `${SITE_URL}/blog`, priority: 0.8 },
    { loc: `${SITE_URL}/countries`, priority: 0.7 },
    { loc: `${SITE_URL}/expat`, priority: 0.7 },
    { loc: `${SITE_URL}/expat/events`, priority: 0.6 },
    { loc: `${SITE_URL}/expat/stories`, priority: 0.6 },
    { loc: `${SITE_URL}/expat/benefits`, priority: 0.4 },
    ...expatStories.map((s) => ({
      loc: `${SITE_URL}/expat/stories/${s.slug}`,
      lastmod: s.date,
      changefreq: "monthly" as const,
      priority: 0.5,
    })),
    { loc: `${SITE_URL}/governance`, priority: 0.1 },
    { loc: `${SITE_URL}/hr`, priority: 0.2 },
    { loc: `${SITE_URL}/landingBusiness`, priority: 0.9 },
    { loc: `${SITE_URL}/landingIndividual`, priority: 1.0 },
    { loc: `${SITE_URL}/others/help`, priority: 0.5 },
    { loc: `${SITE_URL}/services/currency`, priority: 0.7 },
    { loc: `${SITE_URL}/services/loan`, priority: 0.8 },
    { loc: `${SITE_URL}/services/remit`, priority: 0.8 },
    { loc: `${SITE_URL}/services/saving`, priority: 0.8 },
    { loc: `${SITE_URL}/team`, priority: 0.2 },
    { loc: `${SITE_URL}/others/contact`, priority: 0.4 },
    { loc: `${SITE_URL}/others/rate`, priority: 0.5 },
  ];

  const [postRoutes, countryRoutes] = await Promise.all([
    getBlogRoutes(),
    getCountryRoutes(),
  ]);

  return [...staticRoutes, ...postRoutes, ...countryRoutes];
}
