import { redirect } from "next/navigation";
import type { ReactNode } from "react";
import { Sidebar } from "@/components/shell/Sidebar";
import { Topbar } from "@/components/shell/Topbar";
import { createClient } from "@/lib/supabase/server";

export default async function AppLayout({ children }: { children: ReactNode }) {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();
  if (!user) redirect("/login");

  const { data: profile } = await supabase
    .from("profiles")
    .select("full_name, email, role")
    .eq("id", user.id)
    .single();

  const userLabel = profile?.full_name || profile?.email || user.email || "";

  return (
    <div className="flex min-h-screen">
      <Sidebar />
      <div className="ml-[236px] flex flex-1 flex-col">
        <Topbar userLabel={userLabel} role={profile?.role} />
        <main className="flex-1 px-6 py-6">
          <div className="mx-auto w-full max-w-[1280px]">{children}</div>
        </main>
      </div>
    </div>
  );
}
