import { createClient } from "@/lib/supabase/server"
import { redirect } from "next/navigation"
import { AppSidebar } from "@/components/app-sidebar"
import { TopBar } from "@/components/top-bar"
import type { User } from "@/lib/supabase/database.types"
import { isAdminUser } from "@/lib/auth/is-admin"
import { ensureUserProfile } from "@/lib/auth/ensure-user-profile"
import { SidebarProvider, SidebarInset } from "@/components/ui/sidebar"

export default async function ProtectedLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const supabase = await createClient()

  const { data: { user } } = await supabase.auth.getUser()

  if (!user) {
    redirect("/auth/login")
  }

  const ensureResult = await ensureUserProfile(supabase, user)
  if (!ensureResult.ok) {
    redirect("/auth/error")
  }

  const resolvedRole = isAdminUser(user) ? "admin" : "user"
  const resolvedName =
    (user.user_metadata?.full_name as string | undefined) ??
    (user.user_metadata?.name as string | undefined) ??
    null

  const profile: User = {
    id: user.id,
    email: user.email ?? "",
    full_name: resolvedName,
    role: resolvedRole,
    is_active: true,
    created_at: null,
    updated_at: null,
  }

  return (
    <SidebarProvider>
      <div className="flex flex-col w-full min-h-screen">
        {/* Top bar — spans full width including over the sidebar */}
        <TopBar user={profile} />
        {/* Sidebar + Content */}
        <div className="flex flex-1">
          <AppSidebar user={profile} />
          <SidebarInset className="bg-[var(--ds-background-layout-default)]">
            <main className="ds-grid-shell flex-1 py-[var(--ds-space-4x)]">
              {children}
            </main>
          </SidebarInset>
        </div>
      </div>
    </SidebarProvider>
  )
}
