import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";
import { NavbarClient } from "@/components/NavbarClient";

export async function Navbar() {
  const cookieStore = await cookies();

  const supabaseUrl = process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL;
  const supabaseAnonKey = process.env.SUPABASE_ANON_KEY || process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

  if (!supabaseUrl || !supabaseAnonKey) {
    // Falls keine Env-Vars da sind, leeren User an Client übergeben
    return <NavbarClient user={null} />;
  }

  const supabase = createServerClient(
    supabaseUrl,
    supabaseAnonKey,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options),
            );
          } catch {
            // Kann in Server Components ignoriert werden, da dort keine Cookies gesetzt werden können
          }
        },
      },
      cookieOptions: {
        name: "webshop-auth-token",
      },
    },
  );

  let user = null;
  let role = "partner";
  try {
    const { data } = await supabase.auth.getUser();
    user = data.user;
    if (user) {
      const { data: dbUser } = await supabase
        .from("users")
        .select("role")
        .eq("id", user.id)
        .single();
      if (dbUser) {
        role = dbUser.role;
      }
    }
  } catch (error) {
    console.error("Fehler beim Abrufen des Users in Navbar:", error);
  }

  return <NavbarClient user={user} role={role} />;
}
