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

export async function POST(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { data: profile } = await supabase.from('user_profiles').select('role').eq('id', user.id).single();
    if (!['administrator', 'admin'].includes(profile?.role || '')) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

    // Fetch all active banned terms
    const { data: bannedTerms } = await supabase.from('banned_terms').select('term, ban_level, site_scope').eq('is_active', true);
    if (!bannedTerms || bannedTerms.length === 0) return NextResponse.json({ matches: [] });

    // Fetch all published posts
    const [nativeRes, importedRes] = await Promise.all([
      supabase.from('native_articles').select('id, title, author_name, published_at, site_id').eq('status', 'published'),
      supabase.from('wp_imported_posts').select('id, title, author_name, wp_published_at').eq('status', 'published'),
    ]);

    const allPosts = [
      ...(nativeRes.data || []).map((p: any) => ({ ...p, published_at: p.published_at, site_id: p.site_id || 1 })),
      ...(importedRes.data || []).map((p: any) => ({ ...p, published_at: p.wp_published_at, site_id: 1 })),
    ];

    const matches: any[] = [];
    for (const post of allPosts) {
      const titleLower = (post.title || '').toLowerCase();
      for (const bt of bannedTerms) {
        const termLower = bt.term.toLowerCase();
        const siteMatch = bt.site_scope === 'both' || (bt.site_scope === 'avbeat' && post.site_id === 1) || (bt.site_scope === 'avbeat' && post.site_id === 2);
        if (siteMatch && titleLower.includes(termLower)) {
          matches.push({ title: post.title, author: post.author_name, published_at: post.published_at, site_id: post.site_id, matched_term: bt.term, ban_level: bt.ban_level });
          break; // one match per post
        }
      }
    }

    return NextResponse.json({ matches });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
