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 { data, error } = await supabase.from('rmp_suppression_keywords').select('*').order('keyword_type').order('keyword');
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  return NextResponse.json({ keywords: 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_suppression_keywords').insert({
    keyword: body.keyword.toLowerCase().trim(),
    keyword_type: body.keyword_type ?? 'unsubscribe',
    active: true,
  }).select().single();

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