import { redirect } from "next/navigation";

import { getActiveContext } from "@/lib/appwrite/active-context";
import { countUnreadNotifications } from "@/lib/appwrite/notification-helpers";
import { getLogoUrl } from "@/lib/appwrite/storage";
import { getUserPrefs } from "@/lib/appwrite/user-prefs-actions";
import type { UserPrefs as ThemePrefs } from "@/lib/appwrite/user-prefs-actions";
import { DashboardShell } from "./dashboard-shell";

export default async function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const ctx = await getActiveContext();
  if (!ctx) redirect("/onboarding");

  const [themePrefs, unreadCount] = (await Promise.all([
    getUserPrefs(),
    countUnreadNotifications(ctx.tenantId),
  ])) as [ThemePrefs, number];

  const company = {
    id: ctx.tenantId,
    name: ctx.settings?.companyName ?? "Çalışma alanı",
    logoUrl: getLogoUrl(ctx.settings?.logo) ?? null,
    kind: (ctx.settings?.kind ?? "lab") as "lab" | "clinic",
  };
  const user = {
    id: ctx.user.id,
    name: ctx.user.name || ctx.user.email,
    email: ctx.user.email,
  };

  return (
    <DashboardShell
      user={user}
      company={company}
      initialPrefs={themePrefs}
      unreadCount={unreadCount}
    >
      {children}
    </DashboardShell>
  );
}
