import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { DIABETES_TYPE_LABELS } from "@/lib/patient";
import { AppShell } from "@/components/AppShell";

export default async function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await auth();
  if (!session?.user) redirect("/auth/login");
  if (!(session.user as { emailVerified?: Date | null }).emailVerified) redirect("/auth/verify-pending");

  const patient = await prisma.patient.findUnique({
    where: { userId: session.user.id },
    select: { firstName: true, lastName: true, diabetesType: true },
  });

  const fullName = patient
    ? `${patient.firstName} ${patient.lastName}`.trim()
    : session.user.name ?? null;
  const initials = fullName
    ? fullName.split(" ").map((w) => w[0]).join("").toUpperCase().slice(0, 2)
    : null;
  const diabetesLabel = patient?.diabetesType
    ? DIABETES_TYPE_LABELS[patient.diabetesType] ?? null
    : null;

  return (
    <AppShell
      fullName={fullName}
      initials={initials}
      diabetesLabel={diabetesLabel}
      plan={(session.user as { plan?: string }).plan ?? "FREE"}
    >
      {children}
    </AppShell>
  );
}
