import Unauthorized from "@/components/unauthorized";
import { auth } from "@/lib/auth";
import { getEventById } from "@/lib/repositories";
import { headers } from "next/headers";
import { notFound, redirect } from "next/navigation";

export default async function Members({
  params,
}: {
  params: Promise<{ eventId: string }>;
}) {
  const requestHeaders = await headers();

  // Get updated session on server-side
  let session = await auth.api.getSession({
    headers: requestHeaders,
  });
  if (!session) redirect("/get-started");

  const { eventId } = await params;
  const event = await getEventById({ id: eventId });
  if (!event) notFound();

  const userTeams = await auth.api.listUserTeams({
    headers: requestHeaders,
  });

  const team = userTeams.find((team) => team.id === event.teamId);
  if (!team) return <Unauthorized />;

  console.log(
    "session.session?.activeOrganizationId",
    session.session?.activeOrganizationId
  );
  console.log("session.session?.activeTeamId", session.session?.activeTeamId);
  console.log("team.organizationId", team.organizationId);
  console.log("team.id", team.id);

  if (
    session.session?.activeOrganizationId !== team.organizationId ||
    session.session?.activeTeamId !== team.id
  ) {
    console.log("setting active organization and team");

    const orgResult = await auth.api.setActiveOrganization({
      body: {
        organizationId: team.organizationId,
      },
      headers: requestHeaders,
    });
    console.log("orgResult", orgResult);

    const teamResult = await auth.api.setActiveTeam({
      body: {
        teamId: team.id,
      },
      headers: requestHeaders,
    });
    console.log("teamResult", teamResult);

    session = await auth.api.getSession({
      headers: requestHeaders,
      query: {
        disableCookieCache: true,
      },
    });
  }

  console.log("session in members page", session);

  return <div>test</div>;
}
