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

/** Punch feed + unmatched queue for the Control Panel card. */
export async function GET(req: Request) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session?.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const url = new URL(req.url);
  const filter = url.searchParams.get("filter") ?? "recent"; // recent | unmatched

  const punches = await prisma.rawPunch.findMany({
    where: {
      institutionId: session.institutionId,
      ...(filter === "unmatched" ? { matchStatus: "UNMATCHED" } : {}),
    },
    orderBy: { punchedAt: "desc" },
    take: filter === "unmatched" ? 200 : 50,
    include: {
      machine: { select: { name: true } },
      student: { select: { roll: true, name: true, nameBn: true } },
      staff: { select: { employeeCode: true, name: true, nameBn: true } },
    },
  });

  return NextResponse.json({
    punches: punches.map((p) => ({
      id: p.id,
      time: p.punchedAt.toISOString(),
      source: p.source,
      machine: p.machine?.name ?? null,
      identifier: p.identifier,
      matchStatus: p.matchStatus,
      student: p.student ? { roll: p.student.roll, name: p.student.name, nameBn: p.student.nameBn } : null,
      staff: p.staff ? { employeeCode: p.staff.employeeCode, name: p.staff.name, nameBn: p.staff.nameBn } : null,
    })),
  });
}
