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');

  let query = supabase.from('rmp_email_sending_domains').select('*').order('site').order('sort_order');
  if (site) query = query.eq('site', site);

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

  return NextResponse.json({ domains: 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_sending_domains').insert({
    site: body.site,
    domain: body.domain,
    domain_type: body.domain_type ?? 'subdomain',
    is_primary: body.is_primary ?? false,
    sort_order: body.sort_order ?? 0,
    is_active: false,
    dns_fully_verified: false,
  }).select().single();

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