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

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

  const { id } = await params;
  const supabase = await createClient();
  const body = await request.json();

  const { data: domain } = await supabase.from('rmp_email_sending_domains').select('*').eq('id', id).single();
  if (!domain) return NextResponse.json({ error: 'Domain not found' }, { status: 404 });

  await supabase.from('rmp_email_sending_domains').update({
    bypass_verification: true,
    bypass_reason: body.reason,
    bypass_set_by: auth.user?.email ?? 'admin',
    bypass_set_at: new Date().toISOString(),
  }).eq('id', id);

  // Log
  await supabase.from('rmp_email_dns_log').insert({
    domain_id: id,
    check_type: 'bypass_override',
    passed: true,
    result_detail: `Bypass set: ${body.reason}`,
  });

  return NextResponse.json({ ok: true });
}
