import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { signReportToken, type ReportVerifyPayload } from "@/lib/verify-token";

/** Mint a signed verification token for a printable report QR (exam
    schedule / inventory). The QR encodes /verify/result?t=<token> and the
    public verify endpoint confirms the report was issued by this
    institution — same trust model as the marksheet QRs. */
export async function GET(req: Request) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const url = new URL(req.url);
  const type = url.searchParams.get("type") ?? "";
  const id = url.searchParams.get("id") ?? "all";

  if (type !== "exam-schedule" && type !== "inventory") {
    return NextResponse.json({ error: "Invalid report type" }, { status: 400 });
  }

  if (type === "exam-schedule") {
    const examId = Number(id);
    if (!examId) return NextResponse.json({ error: "EXAM_REQUIRED" }, { status: 400 });
    const exam = await prisma.exam.findFirst({
      where: { id: examId, OR: [{ institutionId: session.institutionId }, { branchId: session.institutionId }] },
      select: { id: true },
    });
    if (!exam) return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  const payload: ReportVerifyPayload = {
    i: session.institutionId,
    rt: type,
    k: type === "exam-schedule" ? String(id) : "all",
    ts: Date.now(),
  };

  return NextResponse.json({ token: signReportToken(payload) });
}
