import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { verifyResultToken, verifyReportToken } from "@/lib/verify-token";

/**
 * Public result-copy / report verification — the QR on each marksheet and
 * printable report (exam schedule, inventory) encodes /verify/result?t=…;
 * this endpoint validates the signed token and returns the matching record
 * so scanners can confirm the document was issued by the institution.
 */
export async function GET(req: Request) {
  const url = new URL(req.url);
  const token = url.searchParams.get("t") ?? "";
  const check = verifyResultToken(token);
  if (!check.ok) {
    // not a marksheet token — maybe a printable-report token
    const report = verifyReportToken(token);
    if (report.ok) {
      const institution = await prisma.institution.findUnique({
        where: { id: report.payload.i },
        select: { name: true },
      });
      if (!institution) return NextResponse.json({ valid: false }, { status: 200 });
      let title = "";
      if (report.payload.rt === "exam-schedule") {
        const exam = await prisma.exam.findUnique({
          where: { id: Number(report.payload.k) },
          select: { name: true },
        });
        title = exam?.name ?? "";
      }
      return NextResponse.json({
        valid: true,
        institution: { name: institution.name },
        report: {
          type: report.payload.rt,
          title,
          generatedAt: new Date(report.payload.ts).toISOString(),
        },
      });
    }
    return NextResponse.json({ valid: false }, { status: 200 });
  }
  const { i, s, t, g } = check.payload;

  const student = await prisma.student.findFirst({
    where: { id: s, institutionId: i },
    select: {
      id: true, roll: true, name: true, nameBn: true, status: true,
      classItem: { select: { name: true, nameBn: true } },
      institution: { select: { id: true, name: true, type: true } },
    },
  });
  if (!student) return NextResponse.json({ valid: false }, { status: 200 });

  // live totals for the same key: recompute quickly by counting this
  // student's marks in the institution's exams is complex; the signed
  // token itself guarantees the numbers were issued by the institution.
  return NextResponse.json({
    valid: true,
    institution: { name: student.institution.name },
    student: {
      roll: student.roll,
      name: student.name,
      nameBn: student.nameBn,
      className: student.classItem?.name ?? null,
      status: student.status,
    },
    issued: { totalObtained: t, grade: g },
  });
}
