import { getServerSession } from "next-auth";
import { authOptions } from "../../lib/auth/options";
import { prisma } from "../../lib/db/prisma";

type Props = {
  targetType: string;
  targetId: string;
  title?: string;
};

export async function AuditPanel({ targetType, targetId, title = "Audit events" }: Props) {
  const session = await getServerSession(authOptions);
  const canViewAudit = session?.user.systemRole === "SYSTEM_ADMIN" || session?.user.permissions.includes("manage_settings");
  if (!canViewAudit) return null;

  const logs = await prisma.auditLog.findMany({
    where: {
      targetType,
      targetId,
      ...(session?.user.systemRole === "SYSTEM_ADMIN" ? {} : { organizationId: session?.user.organizationId! })
    },
    take: 10,
    orderBy: { createdAt: "desc" },
    include: { actor: { select: { name: true, email: true } } }
  });

  return (
    <section className="mt-6 rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h2 className="text-lg font-semibold">{title}</h2>
        <a className="text-sm font-semibold text-brand-secondary" href={`/admin/audit-logs?targetType=${encodeURIComponent(targetType)}`}>Open audit log</a>
      </div>
      <div className="mt-4 grid gap-2">
        {logs.length ? logs.map((log) => (
          <div className="rounded-lg bg-brand-paper p-3" key={log.id}>
            <p className="font-medium">{log.action}</p>
            <p className="text-sm text-slate-500">{log.createdAt.toLocaleString()} · {log.actor?.name ?? log.actor?.email ?? "System"}</p>
            {log.metadata ? <p className="mt-1 max-w-full truncate font-mono text-xs text-slate-500">{log.metadata}</p> : null}
          </div>
        )) : <p className="text-sm text-slate-500">No audit events recorded for this item yet.</p>}
      </div>
    </section>
  );
}
