// components/ProtectedRoute.tsx
import { useSession, signIn } from "next-auth/react";
import { useEffect, ReactNode } from "react";
import { useRouter } from 'next/router';
import { UserRole } from '../Enums/UserRole';
import { getSession } from "next-auth/react";

interface ProtectedRouteProps {
    children: ReactNode;
    allowedRoles: UserRole[];
    deniedMessage?: string;
    bypass?: boolean;
}

const ProtectedRoute = ({ children, allowedRoles, deniedMessage, bypass = false }: ProtectedRouteProps) => {
    const { data: session, status } = useSession()
    const router = useRouter();

    useEffect(() => {
        console.log("session.role:" + session?.user?.role);
        if (!status || status === "unauthenticated") {
            // Redirect to the sign-in page
            if (!bypass) {
                signIn();
            }
            return null;
        }
        else {
            console.log("session.role:" + session?.user?.role);
        }
    }, [session, status, router]);
    if (status === "authenticated") {
        const userRole = session.user.role as UserRole; // Assuming role is part of the session object

        // Grant access if allowedRoles is not defined, or if the user's role is among the allowed roles
        if (bypass || !allowedRoles || (allowedRoles && allowedRoles.includes(userRole))) {
            return <>{children}</>;
        }

        // Handle denied access
        if (deniedMessage !== undefined) {
            return <div>{deniedMessage}</div>;
        }
        return <div>Нямате достъп до тази страница. Ако мислите, че това е грешка, моля, свържете се с администраторите</div>;
    }

    if (status === "loading") {
        return <div>Зареждане...</div>;
    }
    if (!session) return <a href="/api/auth/signin">Защитено съдържание. Впишете се.. </a>
    return children;
};

export default ProtectedRoute;
export async function serverSideAuth({ req, allowedRoles }) {
    const session = await getSession({ req });

    if (!session || (allowedRoles && !allowedRoles.includes(session.user.role))) {
        // User is not authenticated or doesn't have the required role
        return {
            redirect: {
                destination: '/api/auth/signin', // Redirect to the sign-in page
                permanent: false,
            },
        };
    }

    // Return the session if the user is authenticated and has the required role
    return { session };
}
