import { redirect } from "next/navigation";
import { and, eq, sql } from "drizzle-orm";
import { getSession } from "@/lib/auth";
import { db } from "@/db";
import { alerts, tenants } from "@/db/schema";
import { Shell } from "@/components/shell";
import { ToastProvider } from "@/components/toast";
import { logoutAction } from "../login/actions";
import { unreadNotificationCount } from "@/lib/notifications";
import { alertScope } from "@/lib/alerts-scope";

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const session = await getSession();
  if (!session) redirect("/login");

  // Số cảnh báo chưa xử lý hiển thị trên menu — NVKD không xem mục này.
  let alertCount = 0;
  if (session.role !== "SALES") {
    const [row] = await db
      .select({ count: sql<number>`count(*)::int` })
      .from(alerts)
      .where(and(await alertScope(session), eq(alerts.status, "OPEN")));
    alertCount = Number(row?.count ?? 0);
  }

  // Logo cố tình không nằm trong SessionUser/JWT — cookie phiên đăng nhập
  // giới hạn dung lượng, nhét ảnh base64 vào đó sẽ tràn cookie mỗi request.
  const [tenant] = await db
    .select({ logoDataUrl: tenants.logoDataUrl })
    .from(tenants)
    .where(eq(tenants.id, session.tenantId))
    .limit(1);

  const notificationCount = await unreadNotificationCount(session);

  return (
    <ToastProvider>
      <Shell session={session} alertCount={alertCount} notificationCount={notificationCount} logoDataUrl={tenant?.logoDataUrl ?? null} onLogout={logoutAction}>
        {children}
      </Shell>
    </ToastProvider>
  );
}
