import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { generateSEOMeta, RMPSite } from '@/lib/content/contentPipeline';

/**
 * POST /api/content/seo-batch
 * Batch-generates missing SEO meta for all articles missing meta_title or meta_description.
 * Accepts optional { site } to limit scope.
 */
export async function POST(req: NextRequest) {
  try {
    const body = await req.json().catch(() => ({}));
    const site: RMPSite | undefined = body.site;

    const supabase = await createClient();

    // Fetch articles missing meta from both tables
    let importedQuery = supabase
      .from('wp_imported_posts')
      .select('id, title, content, meta_title, meta_description, site_id')
      .eq('status', 'published')
      .or('meta_title.is.null,meta_description.is.null');

    let nativeQuery = supabase
      .from('native_articles')
      .select('id, title, content, meta_title, meta_description, site_id')
      .eq('status', 'published')
      .or('meta_title.is.null,meta_description.is.null');

    if (site) {
      importedQuery = importedQuery.eq('site_id', site);
      nativeQuery = nativeQuery.eq('site_id', site);
    }

    const [{ data: imported }, { data: native }] = await Promise.all([
      importedQuery,
      nativeQuery,
    ]);

    const allMissing = [
      ...(imported || []).map((a) => ({ ...a, source: 'imported' as const })),
      ...(native || []).map((a) => ({ ...a, source: 'native' as const })),
    ];

    if (allMissing.length === 0) {
      return NextResponse.json({ updated: 0, message: 'No articles missing SEO meta' });
    }

    // Process up to 20 at a time to avoid timeout
    const batch = allMissing.slice(0, 20);
    let updated = 0;
    const errors: string[] = [];

    for (const article of batch) {
      try {
        const siteId = (article.site_id || 'broadcast-beat') as RMPSite;
        const meta = await generateSEOMeta(article.title, article.content || '', siteId);

        const table = article.source === 'imported' ? 'wp_imported_posts' : 'native_articles';
        const { error } = await supabase
          .from(table)
          .update({
            meta_title: meta.metaTitle,
            meta_description: meta.metaDescription,
          })
          .eq('id', article.id);

        if (!error) updated++;
        else errors.push(`${article.id}: ${error.message}`);
      } catch (e: any) {
        errors.push(`${article.id}: ${e.message}`);
      }
    }

    return NextResponse.json({
      updated,
      remaining: allMissing.length - batch.length,
      total: allMissing.length,
      errors: errors.length > 0 ? errors : undefined,
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
