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

async function requireAdmin(request: NextRequest) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return null;
  const { data: profile } = await supabase
    .from('user_profiles')
    .select('role')
    .eq('id', user.id)
    .single();
  if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
  return user;
}

// GET /api/adops/stats — overview stats for dashboard
export async function GET(request: NextRequest) {
  const user = await requireAdmin(request);
  if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  const supabase = await createClient();

  const [
    { data: activeCampaigns },
    { data: pendingApprovals },
    { data: endingSoon },
    { data: recentCampaigns },
    { data: emailCampaigns },
  ] = await Promise.all([
    supabase.from('ad_campaigns').select('id', { count: 'exact' }).eq('status', 'active'),
    supabase.from('ad_campaigns').select('id', { count: 'exact' }).in('status', ['pending_approval', 'pending_info']),
    supabase.from('ad_campaigns')
      .select('id', { count: 'exact' })
      .eq('status', 'active')
      .lte('end_date', new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]),
    supabase.from('ad_campaigns')
      .select('*')
      .order('created_at', { ascending: false })
      .limit(10),
    supabase.from('adops_email_campaigns')
      .select('id', { count: 'exact' })
      .gte('send_date', new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0]),
  ]);

  // Revenue this month
  const startOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0];
  const { data: monthRevenue } = await supabase
    .from('ad_campaigns')
    .select('agreed_rate')
    .eq('status', 'active')
    .gte('start_date', startOfMonth);

  const totalMonthRevenue = monthRevenue?.reduce((sum, c) => sum + (c.agreed_rate || 0), 0) || 0;

  return NextResponse.json({
    activeCampaigns: activeCampaigns?.length || 0,
    pendingApprovals: pendingApprovals?.length || 0,
    endingSoon: endingSoon?.length || 0,
    emailsSentThisMonth: emailCampaigns?.length || 0,
    revenueThisMonth: totalMonthRevenue,
    recentActivity: recentCampaigns || [],
  });
}
