/**
 * Dynamic sitemap.xml — Next.js serves this at /sitemap.xml.
 *
 * Enumerates the same URLs the default Shopware storefront's sitemap covers:
 * static pages, all storefront categories, and all products. URLs are built
 * with the same canonical-slug helpers the rest of the app uses, so they match
 * what visitors actually land on.
 */
import type { MetadataRoute } from 'next';
import {
  getStorefrontUrl,
  getProducts,
  getNavigation,
  getProductUrl,
  getCategoryUrl,
  ShopwareCategory,
} from '@/lib/shopware-api';

// Regenerate at most hourly (ISR) so we don't re-crawl the catalog per request.
export const revalidate = 3600;

const PAGE_SIZE = 100;
const MAX_PRODUCTS = 5000; // safety cap to bound API calls on large catalogs

function flattenCategories(
  cats: ShopwareCategory[],
  out: ShopwareCategory[] = []
): ShopwareCategory[] {
  for (const c of cats) {
    out.push(c);
    if (c.children?.length) flattenCategories(c.children, out);
  }
  return out;
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const base = (getStorefrontUrl() || '').replace(/\/+$/, '');
  const abs = (path: string) =>
    `${base}${path.startsWith('/') ? '' : '/'}${path}`;
  const now = new Date();

  const entries: MetadataRoute.Sitemap = [
    { url: abs('/'), lastModified: now, changeFrequency: 'daily', priority: 1 },
    { url: abs('/products'), changeFrequency: 'daily', priority: 0.5 },
    { url: abs('/about'), changeFrequency: 'monthly', priority: 0.3 },
    { url: abs('/contact'), changeFrequency: 'monthly', priority: 0.3 },
  ];

  // ── Categories ───────────────────────────────────────────────────────────
  try {
    const tree = await getNavigation('main-navigation', 5);
    for (const c of flattenCategories(tree)) {
      // Skip structural folders and external link categories — only real
      // storefront pages belong in the sitemap.
      if (c.type && c.type !== 'page') continue;
      entries.push({ url: abs(getCategoryUrl(c)), changeFrequency: 'daily', priority: 0.7 });
    }
  } catch (e) {
    console.error('[sitemap] failed to load categories:', e);
  }

  // ── Products (paginated) ──────────────────────────────────────────────────
  try {
    let page = 1;
    let fetched = 0;
    while (fetched < MAX_PRODUCTS) {
      const res = await getProducts({ limit: PAGE_SIZE, page });
      const els = res.elements ?? [];
      if (els.length === 0) break;
      for (const p of els) {
        entries.push({ url: abs(getProductUrl(p)), changeFrequency: 'weekly', priority: 0.6 });
      }
      fetched += els.length;
      if (fetched >= (res.total ?? 0) || els.length < PAGE_SIZE) break;
      page++;
    }
  } catch (e) {
    console.error('[sitemap] failed to load products:', e);
  }

  // Deduplicate by URL (a product can surface under multiple category paths).
  const seen = new Set<string>();
  return entries.filter((e) => {
    if (seen.has(e.url)) return false;
    seen.add(e.url);
    return true;
  });
}
