import { redirect } from "next/navigation";

import { getCurrentAuthContext } from "@/modules/core/server/auth";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

type OrganizationWorkspaceLayoutProps = {
  children: React.ReactNode;
  params: Promise<{
    organizationSlug: string;
  }>;
};

export default async function OrganizationWorkspaceLayout({
  children,
  params,
}: OrganizationWorkspaceLayoutProps): Promise<React.ReactElement> {
  const [{ organizationSlug }, context] = await Promise.all([params, getCurrentAuthContext()]);
  if (!context) {
    redirect("/login");
  }

  const activeSlug = context.organization?.slug;
  if (activeSlug && activeSlug !== organizationSlug) {
    redirect(getWorkspaceHref(activeSlug, "/dashboard"));
  }

  return <>{children}</>;
}
