import { getServerSession } from "next-auth"
import { authOptions } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { NextResponse } from "next/server"

export async function GET() {
  const session = await getServerSession(authOptions)
  if (!session?.user || session.user.role !== "ADMIN") {
    return NextResponse.json({ error: "Não autorizado" }, { status: 403 })
  }

  const now = new Date()
  const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)

  const [
    totalUsers,
    totalDocuments,
    activeSubscriptions,
    recentUsers,
    recentDocuments,
    planDistribution,
  ] = await Promise.all([
    prisma.user.count(),
    prisma.document.count(),
    prisma.subscription.count({ where: { status: "ACTIVE" } }),
    prisma.user.findMany({
      where: { createdAt: { gte: thirtyDaysAgo } },
      select: { createdAt: true },
      orderBy: { createdAt: "asc" },
    }),
    prisma.document.findMany({
      where: { createdAt: { gte: thirtyDaysAgo } },
      select: { createdAt: true },
      orderBy: { createdAt: "asc" },
    }),
    prisma.user.groupBy({
      by: ["plan"],
      _count: { plan: true },
    }),
  ])

  // Aggregate signups by day
  const signupsByDay: Record<string, number> = {}
  const docsByDay: Record<string, number> = {}

  for (let i = 29; i >= 0; i--) {
    const d = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
    const key = d.toISOString().slice(0, 10)
    signupsByDay[key] = 0
    docsByDay[key] = 0
  }

  for (const u of recentUsers) {
    const key = u.createdAt.toISOString().slice(0, 10)
    if (signupsByDay[key] !== undefined) signupsByDay[key]++
  }

  for (const d of recentDocuments) {
    const key = d.createdAt.toISOString().slice(0, 10)
    if (docsByDay[key] !== undefined) docsByDay[key]++
  }

  // Mock revenue based on subscriptions
  const plans: Record<string, number> = {}
  for (const p of planDistribution) {
    plans[p.plan] = p._count.plan
  }
  const mockRevenue =
    (plans["PRO"] || 0) * 97 + (plans["ENTERPRISE"] || 0) * 297

  return NextResponse.json({
    totalUsers,
    totalDocuments,
    activeSubscriptions,
    monthlyRevenue: mockRevenue,
    signupsByDay: Object.entries(signupsByDay).map(([date, count]) => ({ date, count })),
    docsByDay: Object.entries(docsByDay).map(([date, count]) => ({ date, count })),
    planDistribution: plans,
  })
}
