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

/**
 * POST /api/content/generate
 * Generates a new article for the specified site and saves it to the database.
 */
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { site, topic } = body as { site: RMPSite; topic?: string };

    if (!site || !SITE_CONFIGS[site]) {
      return NextResponse.json({ error: 'Invalid site. Must be one of: broadcast-beat, av-beat, backlot-beat, broadcast-engineering' }, { status: 400 });
    }

    const article = await generateArticle(site, topic);

    // Save to Supabase native_articles table
    const supabase = await createClient();
    const { data, error } = await supabase
      .from('native_articles')
      .insert({
        title: article.title,
        content: article.content,
        excerpt: article.excerpt,
        author_name: article.author,
        status: 'draft',
        meta_title: article.metaTitle,
        meta_description: article.metaDescription,
        site_id: site,
        ai_generated: true,
        ai_node: article.node,
        word_count: article.wordCount,
        created_at: article.generatedAt,
      })
      .select('id')
      .single();

    if (error) {
      // Return article even if DB save fails (caller can retry)
      return NextResponse.json({ article, saved: false, dbError: error.message }, { status: 200 });
    }

    return NextResponse.json({ article: { ...article, id: data?.id }, saved: true }, { status: 201 });
  } catch (err: any) {
    const isQueued = err?.message?.startsWith('QUEUED:');
    return NextResponse.json(
      { error: err.message || 'Generation failed', queued: isQueued },
      { status: isQueued ? 202 : 500 }
    );
  }
}
