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

/** Teacher/staff leave self-service: own requests + apply (PENDING until an
    admin decides on the HR page). */

async function resolveStaffId(userId: number): Promise<number | null> {
  const me = await prisma.user.findUnique({ where: { id: userId }, select: { staffId: true } });
  return me?.staffId ?? null;
}

export async function GET() {
  const session = await requireAnyRole([...STAFF_SIDE_ROLES]);
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const staffId = await resolveStaffId(session.userId);
  if (!staffId) return NextResponse.json({ leaves: [] });

  const leaves = await prisma.leaveRequest.findMany({
    where: { staffId },
    orderBy: { createdAt: "desc" },
    select: {
      id: true,
      fromDate: true,
      toDate: true,
      days: true,
      reason: true,
      status: true,
      decidedAt: true,
      createdAt: true,
    },
  });

  return NextResponse.json({ leaves });
}

export async function POST(req: Request) {
  const session = await requireAnyRole([...STAFF_SIDE_ROLES]);
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const staffId = await resolveStaffId(session.userId);
    if (!staffId) return NextResponse.json({ error: "FORBIDDEN" }, { status: 403 });

    const body = await req.json();
    const fromDate = String(body.fromDate ?? "");
    const toDate = String(body.toDate ?? "");
    const reason = String(body.reason ?? "").trim();

    if (!fromDate || !toDate || !reason) {
      return NextResponse.json({ error: "MISSING_FIELDS" }, { status: 400 });
    }
    const from = new Date(fromDate);
    const to = new Date(toDate);
    if (isNaN(from.getTime()) || isNaN(to.getTime()) || to < from) {
      return NextResponse.json({ error: "INVALID_DATES" }, { status: 400 });
    }
    const days = Math.round((to.getTime() - from.getTime()) / 86400000) + 1;

    const leave = await prisma.leaveRequest.create({
      data: {
        institutionId: session.institutionId,
        staffId,
        fromDate: from,
        toDate: to,
        days,
        reason,
      },
      select: { id: true, fromDate: true, toDate: true, days: true, status: true },
    });

    return NextResponse.json({ leave }, { status: 201 });
  } catch {
    return NextResponse.json({ error: "Could not submit leave request" }, { status: 500 });
  }
}
