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

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

// Cap below Google's 50k URL/sitemap hard limit, leaving room for the
// static + author + event entries we add below.
const ARTICLE_CAP = 45000;

function sb() {
  return createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      db: { schema: (process.env.NEXT_PUBLIC_SUPABASE_SCHEMA || 'bb') as 'public' },
      auth: { persistSession: false },
    },
  );
}

async function listAuthorSlugs(): Promise<string[]> {
  try {
    const { data } = await sb().from('author_profiles').select('slug').limit(500);
    return ((data || []) as any[]).map((r) => r.slug).filter(Boolean);
  } catch {
    return [];
  }
}

async function listEventSlugs(): Promise<{ slug: string; updated_at: string }[]> {
  try {
    const { data } = await sb()
      .from('events')
      .select('slug,updated_at,start_date')
      .not('slug', 'is', null)
      .limit(500);
    return ((data || []) as any[]).map((r) => ({
      slug: r.slug,
      updated_at: r.updated_at || r.start_date || new Date().toISOString(),
    }));
  } catch {
    return [];
  }
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const staticPages: MetadataRoute.Sitemap = [
    { url: `${BASE_URL}/`, 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 },
  ];

  // Articles — sourced from bb.wp_imported_posts + bb.ai_rewritten_articles.
  // Emit ONE canonical URL per article (/news/[slug]) rather than the prior
  // duplicate /news/ + /articles/ pair, which wasted crawl budget and
  // pushed us toward the 50k-per-file limit on a 29k-article catalog.
  const articleEntries = await getLegacyRecentSitemapEntries(ARTICLE_CAP);
  const articlePages: MetadataRoute.Sitemap = articleEntries.map(({ 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,
    };
  });

  // Author profile pages (bb.author_profiles)
  const authorSlugs = await listAuthorSlugs();
  const authorPages: MetadataRoute.Sitemap = authorSlugs.map((slug) => ({
    url: `${BASE_URL}/authors/${slug}`,
    lastModified: new Date(),
    changeFrequency: 'weekly' as const,
    priority: 0.5,
  }));

  // Event pages (bb.events)
  const eventList = await listEventSlugs();
  const eventPages: MetadataRoute.Sitemap = eventList.map(({ slug, updated_at }) => ({
    url: `${BASE_URL}/events/${slug}`,
    lastModified: new Date(updated_at),
    changeFrequency: 'weekly' as const,
    priority: 0.7,
  }));

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