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

/** Login audit trail for this institution — HR → Login Audit tab.
 *  Shows every sign-in attempt (success and failure) so admins can audit
 *  member activity. */
export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const logs = await prisma.loginLog.findMany({
    where: { institutionId: session.institutionId },
    orderBy: { createdAt: "desc" },
    take: 200,
  });

  return NextResponse.json({
    logs: logs.map((l) => ({
      id: l.id,
      name: l.name,
      role: l.role,
      identifier: l.identifier,
      success: l.success,
      reason: l.reason,
      ip: l.ip,
      createdAt: l.createdAt,
    })),
  });
}
