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";

type NotificationRow = {
  id: string;
  type: string;
  message: string;
  time: string;
  status: string;
};

function toLocale(date: Date | null) {
  if (!date) {
    return "-";
  }

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

export default async function NotificationsPage() {
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const tenantFilter = session.role === "super_admin" ? {} : { tenantId: session.tenantId };

  const [audits, webhooks] = await Promise.all([
    prisma.auditLog.findMany({
      where: tenantFilter,
      include: { actorUser: true, tenant: true },
      orderBy: { createdAt: "desc" },
      take: 8
    }),
    prisma.webhookEvent.findMany({
      where: tenantFilter,
      include: { tenant: true },
      orderBy: { createdAt: "desc" },
      take: 8
    })
  ]);

  const rowsRaw: Array<NotificationRow & { sortAt: Date }> = [
    ...audits.map((audit) => ({
      id: audit.id,
      type: "Audit",
      message: `${audit.actorUser?.fullName ?? "System"} ${audit.action} ${audit.entityType} ${audit.entityId}`,
      time: toLocale(audit.createdAt),
      status: audit.entityType ? "Info" : "Notice",
      sortAt: audit.createdAt
    })),
    ...webhooks.map((event) => ({
      id: event.id,
      type: "Webhook",
      message: `${event.eventType} · ${event.tenant.name}`,
      time: toLocale(event.createdAt),
      status: event.processStatus,
      sortAt: event.createdAt
    }))
  ].sort((a, b) => b.sortAt.getTime() - a.sortAt.getTime());

  const rows = rowsRaw.slice(0, 12).map((item) => [item.type, item.message, item.time, item.status]);

  return (
    <ShellPage shell="admin" title="Notifications" description="Feed notifikasi lintas modul.">
      <TablePlaceholder
        title="Recent notifications"
        columns={["Type", "Message", "Time", "Status"]}
        rows={rows}
      />
    </ShellPage>
  );
}
