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

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

    const currentYear = new Date().getFullYear();
    const userId = session.user.id;
    const role = session.user.role;

    // Common stats for all roles
    const myBalances = await prisma.leaveBalance.findMany({
      where: { userId, year: currentYear },
      include: { leaveType: true },
    });

    const myRequests = await prisma.leaveRequest.findMany({
      where: { userId },
      orderBy: { createdAt: "desc" },
      take: 5,
      include: { leaveType: true },
    });

    const myPendingCount = await prisma.leaveRequest.count({
      where: { userId, status: "PENDING" },
    });

    const totalUsed = myBalances.reduce((sum, b) => sum + b.used, 0);
    const totalAllocated = myBalances.reduce((sum, b) => sum + b.allocated, 0);

    let stats: any = {
      balances: myBalances,
      recentRequests: myRequests,
      myPendingCount,
      totalUsed,
      totalAllocated,
      totalAvailable: totalAllocated - totalUsed - myBalances.reduce((s, b) => s + b.pending, 0),
    };

    // Manager/Admin stats
    if (role === "MANAGER" || role === "ADMIN") {
      let pendingWhere: any = { status: "PENDING" };

      if (role === "MANAGER") {
        const teamIds = await prisma.user.findMany({
          where: { managerId: userId },
          select: { id: true },
        });
        pendingWhere.userId = { in: teamIds.map((t) => t.id) };
      }

      stats.pendingApprovals = await prisma.leaveRequest.count({ where: pendingWhere });

      stats.pendingRequests = await prisma.leaveRequest.findMany({
        where: pendingWhere,
        include: {
          user: { select: { name: true, department: true } },
          leaveType: true,
        },
        orderBy: { createdAt: "desc" },
        take: 5,
      });
    }

    // Admin-only stats
    if (role === "ADMIN") {
      stats.totalEmployees = await prisma.user.count();
      stats.totalRequestsThisMonth = await prisma.leaveRequest.count({
        where: {
          createdAt: {
            gte: new Date(currentYear, new Date().getMonth(), 1),
          },
        },
      });
      stats.approvedThisMonth = await prisma.leaveRequest.count({
        where: {
          status: "APPROVED",
          updatedAt: {
            gte: new Date(currentYear, new Date().getMonth(), 1),
          },
        },
      });
    }

    return NextResponse.json(stats);
  } catch (error) {
    console.error("Dashboard stats error:", error);
    return NextResponse.json({ error: "Failed to fetch stats" }, { status: 500 });
  }
}
