import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export default async function AuditPage() {
  const logs = await prisma.auditLog.findMany({
    include: { actor: { select: { name: true, email: true } } },
    orderBy: { timestamp: "desc" },
    take: 300,
  });

  return (
    <div className="p-8">
      <h1 className="text-2xl font-semibold mb-6">Audit Logs</h1>
      <div className="rounded-xl border border-slate-800 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-slate-900 text-slate-400 text-left">
            <tr>
              <th className="px-4 py-3">Time</th>
              <th className="px-4 py-3">Actor</th>
              <th className="px-4 py-3">Action</th>
              <th className="px-4 py-3">Target</th>
              <th className="px-4 py-3">Result</th>
              <th className="px-4 py-3">IP</th>
            </tr>
          </thead>
          <tbody>
            {logs.map((l) => (
              <tr key={l.id} className="border-t border-slate-800">
                <td className="px-4 py-3 text-slate-400">{new Date(l.timestamp).toLocaleString()}</td>
                <td className="px-4 py-3">{l.actor?.name ?? "System"}</td>
                <td className="px-4 py-3 font-mono text-xs">{l.action}</td>
                <td className="px-4 py-3 text-slate-400 text-xs">{l.target ?? "—"}</td>
                <td className="px-4 py-3">
                  <span className={l.result === "SUCCESS" ? "text-emerald-400" : "text-red-400"}>{l.result}</span>
                </td>
                <td className="px-4 py-3 text-slate-500 text-xs">{l.ipAddress ?? "—"}</td>
              </tr>
            ))}
            {logs.length === 0 && (
              <tr>
                <td colSpan={6} className="px-4 py-8 text-center text-slate-500">
                  No audit events yet.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
