import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { SIGN_IN_PATH, signInPathWithRedirect } from "@/lib/authRedirect";

type ProtectedRouteProps = {
  children: React.ReactNode;
  /** Optional roles for future RBAC (requires site.auth middleware roles on API). */
  roles?: string[];
};

/**
 * Auth gate: runs before layout, page fetch, or 404 resolution.
 * Only /signin is reachable without a valid session.
 */
export const ProtectedRoute = ({ children, roles }: ProtectedRouteProps) => {
  const { isAuthenticated, loading, user } = useAuth();
  const location = useLocation();

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <p className="text-muted-foreground font-display">Loading…</p>
      </div>
    );
  }

  if (!isAuthenticated) {
    const from = `${location.pathname}${location.search}${location.hash}`;
    return <Navigate to={signInPathWithRedirect(from)} replace state={{ from }} />;
  }

  if (roles?.length) {
    const allowed = roles.some((role) => user?.roles?.includes(role));
    if (!allowed) {
      return <Navigate to={SIGN_IN_PATH} replace />;
    }
  }

  return <>{children}</>;
};
