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

export async function GET(req: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || session.user.role !== "ADMIN") {
      return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
    }

    const { searchParams } = new URL(req.url);
    const year = parseInt(searchParams.get("year") || String(new Date().getFullYear()));

    // Get all leave requests for the year
    const requests = await prisma.leaveRequest.findMany({
      where: {
        startDate: { gte: new Date(year, 0, 1) },
        endDate: { lte: new Date(year, 11, 31) },
      },
      include: {
        user: { select: { name: true, department: true, email: true } },
        leaveType: { select: { name: true } },
      },
      orderBy: { startDate: "asc" },
    });

    // Department summary
    const departments: Record<string, { total: number; approved: number; rejected: number; pending: number }> = {};
    for (const r of requests) {
      const dept = r.user.department;
      if (!departments[dept]) {
        departments[dept] = { total: 0, approved: 0, rejected: 0, pending: 0 };
      }
      departments[dept].total++;
      if (r.status === "APPROVED") departments[dept].approved++;
      if (r.status === "REJECTED") departments[dept].rejected++;
      if (r.status === "PENDING") departments[dept].pending++;
    }

    // Leave type summary
    const leaveTypes: Record<string, { total: number; totalDays: number }> = {};
    for (const r of requests) {
      const lt = r.leaveType.name;
      if (!leaveTypes[lt]) {
        leaveTypes[lt] = { total: 0, totalDays: 0 };
      }
      leaveTypes[lt].total++;
      if (r.status === "APPROVED") leaveTypes[lt].totalDays += r.totalDays;
    }

    // Monthly breakdown
    const monthly = Array.from({ length: 12 }, (_, i) => ({
      month: new Date(year, i).toLocaleString("default", { month: "short" }),
      requests: 0,
      days: 0,
    }));

    for (const r of requests) {
      if (r.status === "APPROVED") {
        const month = r.startDate.getMonth();
        monthly[month].requests++;
        monthly[month].days += r.totalDays;
      }
    }

    // Detailed data for export
    const detailed = requests.map((r) => ({
      employee: r.user.name,
      email: r.user.email,
      department: r.user.department,
      leaveType: r.leaveType.name,
      startDate: r.startDate.toISOString().split("T")[0],
      endDate: r.endDate.toISOString().split("T")[0],
      totalDays: r.totalDays,
      status: r.status,
      reason: r.reason,
    }));

    return NextResponse.json({
      year,
      departments,
      leaveTypes,
      monthly,
      detailed,
      totalRequests: requests.length,
      totalApproved: requests.filter((r) => r.status === "APPROVED").length,
      totalDaysUsed: requests
        .filter((r) => r.status === "APPROVED")
        .reduce((sum, r) => sum + r.totalDays, 0),
    });
  } catch (error) {
    console.error("Reports error:", error);
    return NextResponse.json({ error: "Failed to generate report" }, { status: 500 });
  }
}
