/**
 * /api/admin/stats
 *
 * GET — aggregated live statistics for the admin dashboard
 *
 * Returns:
 *   - total_users, new_users_today, new_users_7d
 *   - total_generations, generations_today, generations_7d
 *   - per_platform breakdown
 *   - daily chart data (last 14 days)
 *   - top 5 most active users
 */

import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";

async function requireAdmin(supabase: ReturnType<typeof createClient>) {
  const { data: { user }, error } = await supabase.auth.getUser();
  if (error || !user) return null;
  const { data: profile } = await supabase
    .from("profiles")
    .select("role")
    .eq("id", user.id)
    .single();
  if (profile?.role !== "admin") return null;
  return user;
}

export async function GET() {
  const supabase = createClient();
  const admin = await requireAdmin(supabase);
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const now = new Date();
  const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString();
  const start7d = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString();
  const start14d = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString();

  // Parallel queries
  const [
    { count: totalUsers },
    { count: newUsersToday },
    { count: newUsers7d },
    { count: totalGenerations },
    { count: generationsToday },
    { count: generations7d },
    { data: platformStats },
    { data: dailyHistory },
    { data: topUsers },
  ] = await Promise.all([
    // Total users
    supabase.from("profiles").select("id", { count: "exact", head: true }),

    // New users today
    supabase
      .from("profiles")
      .select("id", { count: "exact", head: true })
      .gte("created_at", startOfToday),

    // New users last 7 days
    supabase
      .from("profiles")
      .select("id", { count: "exact", head: true })
      .gte("created_at", start7d),

    // Total generations
    supabase.from("prompt_history").select("id", { count: "exact", head: true }),

    // Generations today
    supabase
      .from("prompt_history")
      .select("id", { count: "exact", head: true })
      .gte("created_at", startOfToday),

    // Generations last 7 days
    supabase
      .from("prompt_history")
      .select("id", { count: "exact", head: true })
      .gte("created_at", start7d),

    // Per-platform breakdown (total)
    supabase
      .from("prompt_history")
      .select("platform"),

    // Daily history last 14 days (for chart)
    supabase
      .from("prompt_history")
      .select("created_at, platform")
      .gte("created_at", start14d)
      .order("created_at", { ascending: true }),

    // Top 5 users by generation count
    supabase
      .from("profiles")
      .select("id, email, full_name, usage_count, plan, role")
      .order("usage_count", { ascending: false })
      .limit(5),
  ]);

  // Aggregate per-platform
  const platformCounts: Record<string, number> = {};
  (platformStats ?? []).forEach((row) => {
    platformCounts[row.platform] = (platformCounts[row.platform] ?? 0) + 1;
  });

  // Build daily chart — group by date
  const dailyMap: Record<string, { date: string; count: number; platforms: Record<string, number> }> = {};
  (dailyHistory ?? []).forEach((row) => {
    const date = row.created_at.slice(0, 10); // "YYYY-MM-DD"
    if (!dailyMap[date]) {
      dailyMap[date] = { date, count: 0, platforms: {} };
    }
    dailyMap[date].count++;
    dailyMap[date].platforms[row.platform] = (dailyMap[date].platforms[row.platform] ?? 0) + 1;
  });

  // Fill missing days with 0
  const chartData: { date: string; count: number; platforms: Record<string, number> }[] = [];
  for (let i = 13; i >= 0; i--) {
    const d = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
    const key = d.toISOString().slice(0, 10);
    chartData.push(dailyMap[key] ?? { date: key, count: 0, platforms: {} });
  }

  return NextResponse.json({
    users: {
      total: totalUsers ?? 0,
      new_today: newUsersToday ?? 0,
      new_7d: newUsers7d ?? 0,
    },
    generations: {
      total: totalGenerations ?? 0,
      today: generationsToday ?? 0,
      last_7d: generations7d ?? 0,
    },
    per_platform: platformCounts,
    chart: chartData,
    top_users: topUsers ?? [],
    fetched_at: new Date().toISOString(),
  });
}
