import { getSupabaseClient } from "@/lib/supabase";
import BigCalendar from "./BigCalender";
import { auth } from "@clerk/nextjs/server";

const BigCalendarContainer = async ({
  type,
  id,
}: {
  type: "teacherId" | "classId";
  id: string | number | number[];
}) => {
  const { sessionClaims } = auth();
  const schoolId = (sessionClaims?.metadata as { schoolId?: string })?.schoolId;

  const supabase = await getSupabaseClient();

  let query = supabase.from("Lesson").select("*");
  if (schoolId) {
    query = query.eq("schoolId", schoolId);
  }

  if (type === "teacherId") {
    query = query.eq("teacherId", id as string);
  } else {
    const classIds = Array.isArray(id) ? id : [id];
    if (classIds.length > 0) {
      query = query.in("classId", classIds as number[]);
    }
  }

  const { data: rawData, error } = await query;
  if (error) {
    console.error("Error fetching calendar lessons:", error);
  }

  const dataRes = rawData || [];

  const data = dataRes.map((lesson) => ({
    id: lesson.id,
    title: lesson.name,
    start: new Date(lesson.startTime),
    end: new Date(lesson.endTime),
  }));

  return (
    <div className="">
      <BigCalendar data={data} />
    </div>
  );
};

export default BigCalendarContainer;
