// 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;
    autoRedirect?: boolean;
}

const ProtectedRoute = ({ children, allowedRoles, deniedMessage, bypass = false, autoRedirect = 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 (autoRedirect) {
                signIn();
            }
        }
        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 className="flex items-center justify-center min-h-screen">
                    <div className="text-center">
                        <h1 className="text-2xl font-bold mb-4 text-blue-500">{session?.user?.email},</h1>
                        <p className="mb-6">{`Нямате достъп до тази страница.`}</p>
                        <p className="mb-6">{`Ако мислите, че това е грешка, моля, свържете се с администраторите`}</p>
                    </div>
                </div>
            </>);

    }

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

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 };
}
// Static method to check if the user has a specific role
ProtectedRoute.IsInRole = async (roleName) => {
    const session = await getSession();
    return (session && session.user && session.user.role === roleName) || false;
};

ProtectedRoute.GetCurrentUserId = async () => {
    const session = await getSession();
    return session && session.user && session.user.id;
}