import { MetadataRoute } from 'next';
import { getLegacyRecentSitemapEntries } from '@/lib/articles/legacy-source';

const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://broadcastbeat.com';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  // Static pages
  const staticPages: MetadataRoute.Sitemap = [
    { url: `${BASE_URL}/`, lastModified: new Date(), changeFrequency: 'daily', priority: 1.0 },
    { url: `${BASE_URL}/home-page`, lastModified: new Date(), changeFrequency: 'daily', priority: 1.0 },
    { url: `${BASE_URL}/news`, lastModified: new Date(), changeFrequency: 'hourly', priority: 0.9 },
    { url: `${BASE_URL}/gear`, lastModified: new Date(), changeFrequency: 'daily', priority: 0.8 },
    { url: `${BASE_URL}/technology`, lastModified: new Date(), changeFrequency: 'daily', priority: 0.8 },
    { url: `${BASE_URL}/show-coverage`, lastModified: new Date(), changeFrequency: 'weekly', priority: 0.8 },
    { url: `${BASE_URL}/forum`, lastModified: new Date(), changeFrequency: 'daily', priority: 0.8 },
    { url: `${BASE_URL}/about`, lastModified: new Date(), changeFrequency: 'monthly', priority: 0.6 },
    { url: `${BASE_URL}/advertise`, lastModified: new Date(), changeFrequency: 'monthly', priority: 0.6 },
    { url: `${BASE_URL}/contributor`, lastModified: new Date(), changeFrequency: 'monthly', priority: 0.5 },
    { url: `${BASE_URL}/marketplace`, lastModified: new Date(), changeFrequency: 'daily', priority: 0.7 },
    { url: `${BASE_URL}/marketplace/jobs`, lastModified: new Date(), changeFrequency: 'daily', priority: 0.7 },
    { url: `${BASE_URL}/marketplace/gigs`, lastModified: new Date(), changeFrequency: 'daily', priority: 0.7 },
    { url: `${BASE_URL}/privacy`, lastModified: new Date(), changeFrequency: 'yearly', priority: 0.3 },
    { url: `${BASE_URL}/terms`, lastModified: new Date(), changeFrequency: 'yearly', priority: 0.3 },
  ];

  // Dynamic article pages — sourced from bb.wp_imported_posts (DB).
  const articleEntries = await getLegacyRecentSitemapEntries(5000);
  const articlePages: MetadataRoute.Sitemap = articleEntries.flatMap(({ slug, date }) => {
    const lastModified = new Date(date);
    const safe = isNaN(lastModified.getTime()) ? new Date() : lastModified;
    return [
      {
        url: `${BASE_URL}/news/${slug}`,
        lastModified: safe,
        changeFrequency: 'monthly' as const,
        priority: 0.7,
      },
      {
        url: `${BASE_URL}/articles/${slug}`,
        lastModified: safe,
        changeFrequency: 'monthly' as const,
        priority: 0.6,
      },
    ];
  });

  // Attempt to ping Google Search Console (fire-and-forget, non-blocking)
  const sitemapUrl = encodeURIComponent(`${BASE_URL}/sitemap.xml`);
  fetch(`https://www.google.com/ping?sitemap=${sitemapUrl}`, { method: 'GET' }).catch(() => {
    // Silently ignore — ping is best-effort
  });

  return [...staticPages, ...articlePages];
}