import { NextRequest, NextResponse } from 'next/server';
import { requirePermission } from '@/shared/admin/guards';
import { PERMISSIONS } from '@/shared/admin/permissions';
import { createAdminClient } from '@/shared/db/supabase-client';

// --- ASA GENERATED START ---
// Route handler for admin/dashboard slice.
// Returns overview stats for admin dashboard.
// Security: requires admin.access permission (server-side).
// --- ASA GENERATED END ---

// --- USER CODE START ---

export async function GET(request: NextRequest): Promise<NextResponse> {
  const { response } = await requirePermission(request, PERMISSIONS.ADMIN_ACCESS);
  if (response) return response;

  const supabase = createAdminClient();

  // Parallel queries for dashboard stats
  const [usersResult, subsResult, recentActivityResult] = await Promise.all([
    supabase.from('profiles').select('id', { count: 'exact', head: true }),
    supabase.from('subscriptions').select('plan, status'),
    supabase
      .from('audit_log')
      .select('action, actor_email, created_at')
      .order('created_at', { ascending: false })
      .limit(10),
  ]);

  const totalUsers = usersResult.count ?? 0;
  const subscriptions = subsResult.data ?? [];

  const planCounts: Record<string, number> = {};
  const statusCounts: Record<string, number> = {};
  for (const sub of subscriptions) {
    planCounts[sub.plan] = (planCounts[sub.plan] ?? 0) + 1;
    statusCounts[sub.status] = (statusCounts[sub.status] ?? 0) + 1;
  }

  return NextResponse.json({
    stats: {
      total_users: totalUsers,
      plans: planCounts,
      statuses: statusCounts,
    },
    recent_activity: recentActivityResult.data ?? [],
  });
}

// --- USER CODE END ---
