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

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 WebhookLogsPage() {
  const session = await getSession();
  if (!session || session.role !== "super_admin") {
    redirect("/unauthorized");
  }

  const events = await prisma.webhookEvent.findMany({
    include: { tenant: true, channel: true },
    orderBy: { createdAt: "desc" },
    take: 120
  });

  return (
    <ShellPage shell="super-admin" title="Webhook Logs" description="Raw provider event logs dan process status.">
      <TablePlaceholder
        title="Webhook events"
        columns={["Event type", "Provider event ID", "Tenant", "Status"]}
        rows={events.map((event) => [
          `${event.eventType} (${event.channel?.channelName ?? "global"})`,
          event.providerEventId ?? "-",
          event.tenant.name,
          `${event.processStatus} · ${formatTime(event.createdAt)}`
        ])}
      />
    </ShellPage>
  );
}
