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 today = new Date().toISOString().split('T')[0];
  const in30 = new Date(Date.now() + 30 * 86400000).toISOString().split('T')[0];
  const monthStart = `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}-01`;

  const [activeR, expiring30R, expiredMonthR, compedR, unpaidR, emailR] = await Promise.all([
    supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).eq('flight_status', 'active'),
    supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).in('flight_status', ['active', 'scheduled']).lte('end_date', in30).gte('end_date', today),
    supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).eq('flight_status', 'expired').gte('end_date', monthStart),
    supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).eq('is_comp', true).eq('flight_status', 'active'),
    supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).eq('is_paid', false).eq('flight_status', 'active'),
    supabase.from('rmp_io_extensions').select('id', { count: 'exact', head: true }).not('email_scheduled_date', 'is', null).is('email_sent_at', null),
  ]);

  return NextResponse.json({
    active: activeR.count ?? 0,
    expiring_30d: expiring30R.count ?? 0,
    expired_month: expiredMonthR.count ?? 0,
    comped: compedR.count ?? 0,
    unpaid_active: unpaidR.count ?? 0,
    email_scheduled: emailR.count ?? 0,
  });
}
