import { useIdentityAuthSession } from "@erp/identity/client";
import { LoadingOverlay } from "@repo/rdx-ui/components";
import type { ReactNode } from "react";
import { Navigate, useLocation } from "react-router-dom";

interface RequireCompanyRouteGuardProps {
  children: ReactNode;
}

export const RequireCompanyRouteGuard = ({ children }: RequireCompanyRouteGuardProps) => {
  const location = useLocation();
  const { activeCompany, availableCompanies, isLoading } = useIdentityAuthSession();

  if (isLoading) {
    return <LoadingOverlay />;
  }

  if (activeCompany) {
    return <>{children}</>;
  }

  const returnTo = `${location.pathname}${location.search}`;

  if (availableCompanies.length === 0) {
    return <Navigate replace to="/no-companies" />;
  }

  return <Navigate replace to={`/company-selection?returnTo=${encodeURIComponent(returnTo)}`} />;
};
