import DashboardShell from "@/components/DashboardShell";
import { currentUser } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";
import { getSupabaseClient } from "@/lib/supabase";

export default async function DashboardLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const user = await currentUser();

  if (!user) {
    redirect("/sign-in");
  }

  const role = user.publicMetadata.role as string;
  const teacherType = user.publicMetadata.teacherType as string | undefined;
  const activeSchoolId = user.publicMetadata.schoolId as string | undefined;

  const supabase = await getSupabaseClient();

  let schools: { id: string; name: string }[] = [];

  if (role === "admin") {
    const { data } = await supabase
      .from("School")
      .select("id, name")
      .eq("adminId", user.id);
    schools = data || [];
  } else if (role === "teacher") {
    const { data: mappings } = await supabase
      .from("TeacherSchool")
      .select("schoolId")
      .eq("teacherId", user.id);

    const schoolIds = (mappings || []).map((m: any) => m.schoolId);
    if (schoolIds.length > 0) {
      const { data } = await supabase
        .from("School")
        .select("id, name")
        .in("id", schoolIds);
      schools = data || [];
    }
  }

  const canManageSchool =
    role === "admin" ||
    (role === "teacher" &&
      (teacherType === "INDEPENDENT" || teacherType === "AGENCY"));

  const userMetadata = {
    firstName: user.firstName,
    lastName: user.lastName,
    role: role,
    teacherType,
    activeSchoolId,
    schools,
  };

  return (
    <DashboardShell
      role={role}
      userMetadata={userMetadata}
      canManageSchool={canManageSchool}
    >
      {children}
    </DashboardShell>
  );
}
