import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

async function assertSuperAdmin(userId: string) {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { isSuperAdmin: true },
  });
  return user?.isSuperAdmin === true;
}

export async function GET() {
  try {
    const session = await auth();
    const userId = session?.user?.id;
    if (!userId) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
    if (!(await assertSuperAdmin(userId))) return NextResponse.json({ success: false, error: "Accès refusé" }, { status: 403 });

    const now = new Date();
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
    const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);

    const [
      totalOrgs,
      totalUsers,
      newOrgsThisMonth,
      newUsersThisMonth,
      totalInvoicesAmount,
      invoicesThisMonth,
    ] = await prisma.$transaction([
      prisma.organization.count(),
      prisma.user.count(),
      prisma.organization.count({ where: { createdAt: { gte: startOfMonth } } }),
      prisma.user.count({ where: { createdAt: { gte: startOfMonth } } }),
      prisma.invoice.aggregate({ _sum: { total: true } }),
      prisma.invoice.aggregate({ _sum: { total: true }, where: { createdAt: { gte: startOfMonth } } }),
    ]);

    // GroupBy hors transaction pour éviter les conflits de types
    const planCounts = await prisma.subscription.groupBy({
      by: ["plan"],
      _count: { _all: true },
      orderBy: { plan: "asc" },
    });

    const recentOrgs = await prisma.organization.findMany({
      take: 5,
      orderBy: { createdAt: "desc" },
      include: { subscription: { select: { plan: true, status: true } } },
    });

    const planMap: Record<string, number> = {};
    for (const p of planCounts) planMap[p.plan] = p._count._all;

    return NextResponse.json({
      success: true,
      data: {
        totalOrgs,
        totalUsers,
        newOrgsThisMonth,
        newUsersThisMonth,
        plans: { FREE: planMap["FREE"] ?? 0, PRO: planMap["PRO"] ?? 0, BUSINESS: planMap["BUSINESS"] ?? 0 },
        revenue: {
          total: Number(totalInvoicesAmount._sum.total ?? 0),
          thisMonth: Number(invoicesThisMonth._sum.total ?? 0),
        },
        recentOrgs,
        period: { startOfMonth, startOfLastMonth },
      },
    });
  } catch (err: any) {
    console.error("[GET /api/admin/stats]", err);
    return NextResponse.json({ success: false, error: "Erreur serveur", detail: err?.message }, { status: 500 });
  }
}
