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

export async function GET(request: NextRequest) {
  const auth = await requireRmpAdmin();
  if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const supabase = await createClient();
  const { searchParams } = new URL(request.url);
  const site = searchParams.get('site') ?? '';
  const type = searchParams.get('type') ?? '';
  const search = searchParams.get('search') ?? '';

  let query = supabase.from('rmp_email_suppressions').select('*').order('suppressed_at', { ascending: false });
  if (site) query = query.eq('site', site);
  if (type) query = query.eq('suppression_type', type);
  if (search) query = query.ilike('email', `%${search}%`);

  const { data, error } = await query;
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  return NextResponse.json({ suppressions: data ?? [] });
}

export async function POST(request: NextRequest) {
  const auth = await requireRmpAdmin();
  if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const supabase = await createClient();
  const body = await request.json();

  const { data, error } = await supabase.from('rmp_email_suppressions').upsert({
    site: body.site,
    email: body.email.toLowerCase().trim(),
    suppression_type: body.suppression_type ?? 'manual',
    source: 'manual',
    notes: body.notes || null,
    suppressed_by: 'admin',
  }, { onConflict: 'site,email' }).select().single();

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ suppression: data });
}
