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

export async function GET() {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const [
    totalInstitutions,
    pendingInstitutions,
    activeSubscriptions,
    pendingRequests,
    totalPlans,
    totalAcademicItems,
    payments,
    subscriptions,
  ] = await Promise.all([
    prisma.institution.count(),
    prisma.institution.count({ where: { status: "PENDING" } }),
    prisma.subscription.count({ where: { status: "ACTIVE" } }),
    prisma.packageRequest.count({ where: { status: "PENDING" } }),
    prisma.packagePlan.count(),
    prisma.academicItem.count(),
    prisma.payment.findMany({
      orderBy: { paidAt: "desc" },
      take: 6,
      include: {
        institution: { select: { name: true } },
      },
    }),
    prisma.subscription.findMany({
      where: { status: "ACTIVE" },
      include: { payments: { select: { amount: true } } },
    }),
  ]);

  const totalCollected = payments.reduce((sum, p) => sum + Number(p.amount), 0);
  // Due across all active subscriptions
  const totalDue = subscriptions.reduce(
    (sum, s) => sum + Math.max(0, Number(s.totalAmount) - s.payments.reduce((p, x) => p + Number(x.amount), 0)),
    0
  );

  // All-time collected (for revenue stat) + monthly breakdown for last 6 months
  const allPayments = await prisma.payment.findMany({
    select: { amount: true, paidAt: true },
  });
  const allTimeCollected = allPayments.reduce((sum, p) => sum + Number(p.amount), 0);

  const monthly: { key: string; label: string; total: number }[] = [];
  const now = new Date();
  for (let i = 5; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const total = allPayments
      .filter((p) => {
        const pd = new Date(p.paidAt);
        return pd.getFullYear() === d.getFullYear() && pd.getMonth() === d.getMonth();
      })
      .reduce((sum, p) => sum + Number(p.amount), 0);
    monthly.push({
      key: `${d.getFullYear()}-${d.getMonth()}`,
      label: d.toLocaleString("en", { month: "short" }),
      total,
    });
  }

  return NextResponse.json({
    totalInstitutions,
    pendingInstitutions,
    activeSubscriptions,
    pendingRequests,
    totalPlans,
    totalAcademicItems,
    totalCollected: allTimeCollected,
    totalDue,
    recentPayments: payments,
    monthly,
  });
}
