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(date: Date) {
  return new Intl.DateTimeFormat("id-ID", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  }).format(date);
}

function normalizeAction(action: string) {
  return action.includes("failed") ? "Failed" : action.replace(/_/g, " ");
}

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

  const events = await prisma.auditLog.findMany({
    where: {
      OR: [{ action: { contains: "failed" } }, { action: { contains: "permission" } }, { action: { contains: "security" } }]
    },
    orderBy: { createdAt: "desc" },
    take: 30
  });

  return (
    <ShellPage shell="super-admin" title="Security Events" description="Failed logins, suspicious access, dan permission changes.">
      <TablePlaceholder
        title="Security feed"
        columns={["Time", "Type", "Tenant ID", "Status"]}
        rows={events.map((event) => [formatTime(event.createdAt), normalizeAction(event.action), event.tenantId, "Detected"])}
      />
    </ShellPage>
  );
}
