import { NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import type { PrismaClient } from "@prisma/client"

const prisma = db as PrismaClient

export const runtime = "nodejs"

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

    const { searchParams } = new URL(req.url)
    const employeeId = searchParams.get("employeeId")
    const leaveTypeId = searchParams.get("leaveTypeId")

    if (!employeeId || !leaveTypeId) {
      return NextResponse.json({ error: "employeeId and leaveTypeId are required" }, { status: 400 })
    }

    // Get leave allowance for this employee + leave type
    const allowance = await prisma.employeeLeaveAllowance.findUnique({
      where: {
        employeeId_leaveTypeId: {
          employeeId,
          leaveTypeId,
        },
      },
    })

    const totalDays = allowance?.days ?? 0

    // Calculate used days from approved and pending requests
    const usedRequests = await prisma.leaveRequest.findMany({
      where: {
        employeeId,
        leaveTypeId,
        status: { in: ["approved", "pending"] },
      },
      select: {
        duration: true,
      },
    })

    const usedDays = usedRequests.reduce((sum, r) => sum + r.duration, 0)
    const remainingDays = Math.max(0, totalDays - usedDays)

    return NextResponse.json({
      totalDays,
      usedDays,
      remainingDays,
      allowanceExists: Boolean(allowance),
    })
  } catch (error) {
    console.error("Error fetching leave balance:", error)
    return NextResponse.json({ error: "Failed to fetch leave balance" }, { status: 500 })
  }
}
