import { redirect } from "next/navigation";

import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { ShellPage } from "@/components/page-templates";
import { TablePlaceholder } from "@/components/placeholders";

function formatTime(value: Date) {
  return new Intl.DateTimeFormat("id-ID", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  }).format(value);
}

export default async function SuperAdminAuditLogPage() {
  const session = await getSession();
  if (!session || session.role !== "super_admin") {
    redirect("/unauthorized");
  }

  const events = await prisma.auditLog.findMany({
    include: { tenant: true, actorUser: true },
    orderBy: { createdAt: "desc" },
    take: 80
  });

  return (
    <ShellPage shell="super-admin" title="Audit Log" description="Log governance lintas tenant dan modul.">
      <TablePlaceholder
        title="Audit events"
        columns={["Time", "Tenant", "Actor", "Action", "Entity"]}
        rows={events.map((event) => [
          formatTime(event.createdAt),
          event.tenant.name,
          event.actorUser?.fullName ?? "System",
          event.action,
          event.entityId
        ])}
      />
    </ShellPage>
  );
}
