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

const PRESS_RELEASE_PATTERNS = [
  /for immediate release/i,
  /is pleased to announce/i,
  /announced today/i,
  /press release/i,
  /contact:\s/i,
  /###\s*$/m,
  /about\s+[A-Z][a-z]+\s+[A-Z]/,
];

function isPressRelease(content: string): boolean {
  return PRESS_RELEASE_PATTERNS.filter((p) => p.test(content)).length >= 2;
}

/**
 * GET /api/content/press-releases
 * Returns all articles that appear to be unedited press releases.
 */
export async function GET() {
  try {
    const supabase = await createClient();

    const { data: imported, error: e1 } = await supabase
      .from('wp_imported_posts')
      .select('id, title, content, status, created_at, meta_title, meta_description')
      .eq('status', 'published')
      .order('created_at', { ascending: true });

    const { data: native, error: e2 } = await supabase
      .from('native_articles')
      .select('id, title, content, status, created_at, meta_title, meta_description')
      .eq('status', 'published')
      .order('created_at', { ascending: true });

    if (e1 || e2) {
      return NextResponse.json({ error: 'Failed to fetch articles' }, { status: 500 });
    }

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

    const pressReleases = allArticles.filter((a) => isPressRelease(a.content || ''));

    return NextResponse.json({
      total: pressReleases.length,
      pressReleases: pressReleases.map((a) => ({
        id: a.id,
        title: a.title,
        source: a.source,
        created_at: a.created_at,
      })),
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

/**
 * POST /api/content/press-releases
 * Rewrites a specific press release into editorial content.
 */
export async function POST(req: NextRequest) {
  try {
    const { articleId, source, site } = await req.json() as {
      articleId: string;
      source: 'imported' | 'native';
      site: RMPSite;
    };

    const supabase = await createClient();
    const table = source === 'imported' ? 'wp_imported_posts' : 'native_articles';

    const { data: article, error } = await supabase
      .from(table)
      .select('id, title, content')
      .eq('id', articleId)
      .single();

    if (error || !article) {
      return NextResponse.json({ error: 'Article not found' }, { status: 404 });
    }

    const rewrite = await rewritePressRelease(
      String(article.id),
      article.title,
      article.content || '',
      site
    );

    // Save rewritten version as new native article, keep original as archived
    const { data: newArticle, error: saveError } = await supabase
      .from('native_articles')
      .insert({
        title: rewrite.newTitle,
        content: rewrite.content,
        author_name: 'James Mercer',
        status: 'published',
        meta_title: rewrite.metaTitle,
        meta_description: rewrite.metaDescription,
        site_id: site,
        ai_generated: true,
        ai_node: rewrite.node,
        original_press_release_id: articleId,
        created_at: new Date().toISOString(),
      })
      .select('id')
      .single();

    // Archive original
    if (!saveError) {
      await supabase.from(table).update({ status: 'archived' }).eq('id', articleId);
    }

    return NextResponse.json({
      rewrite,
      saved: !saveError,
      newId: newArticle?.id,
    });
  } catch (err: any) {
    const isQueued = err?.message?.startsWith('QUEUED:');
    return NextResponse.json(
      { error: err.message, queued: isQueued },
      { status: isQueued ? 202 : 500 }
    );
  }
}
