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 now = new Date();
  const monthStart = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-01`;

  const [domainsR, sendsR, suppressionsR] = await Promise.all([
    supabase.from('rmp_email_sending_domains').select('site, sends_today, blacklisted'),
    supabase.from('rmp_email_send_log').select('id', { count: 'exact', head: true }).gte('created_at', monthStart),
    supabase.from('rmp_email_suppressions').select('site'),
  ]);

  const domains = domainsR.data ?? [];
  const sends_today = domains.reduce((s: number, d: any) => s + (d.sends_today ?? 0), 0);
  const sends_month = sendsR.count ?? 0;
  const blacklisted = domains.filter((d: any) => d.blacklisted).length;

  // Suppressions by site
  const suppressions_by_site: Record<string, number> = {};
  for (const s of (suppressionsR.data ?? [])) {
    suppressions_by_site[s.site] = (suppressions_by_site[s.site] ?? 0) + 1;
  }
  const total_suppressions = (suppressionsR.data ?? []).length;

  return NextResponse.json({ sends_today, sends_month, total_suppressions, blacklisted, suppressions_by_site });
}
