"use client";

import { useEffect, useRef } from "react";
import { useSession, signOut } from "next-auth/react";

const TIMEOUT_MS = 2 * 60 * 60 * 1000; // 2 hours in milliseconds
const CHECK_INTERVAL_MS = 60 * 1000;   // Check every 1 minute for better UX

export function SessionTimeoutGuard() {
    const { data: session, status } = useSession();
    const checkRef = useRef<NodeJS.Timeout | null>(null);
    const forceLogoutRef = useRef<NodeJS.Timeout | null>(null);

    useEffect(() => {
        if (status !== "authenticated" || !session?.expires) return;

        const expiresAt = new Date(session.expires).getTime();
        const now = Date.now();
        const timeLeft = expiresAt - now;

        const handleSignOut = () => {
            if (typeof window !== "undefined" && window.location.pathname === "/login") {
                signOut({ redirect: false });
            } else {
                signOut({ callbackUrl: "/login", redirect: true });
            }
        };

        // If already expired, force logout immediately
        if (timeLeft <= 0) {
            handleSignOut();
            return;
        }

        // Schedule forced logout at exact expiration time
        forceLogoutRef.current = setTimeout(() => {
            handleSignOut();
        }, timeLeft);

        // Periodic validation (fallback for edge cases)
        checkRef.current = setInterval(() => {
            const remaining = new Date(session.expires).getTime() - Date.now();
            if (remaining <= 0) {
                handleSignOut();
            }
        }, CHECK_INTERVAL_MS);

        return () => {
            if (forceLogoutRef.current) clearTimeout(forceLogoutRef.current);
            if (checkRef.current) clearInterval(checkRef.current);
        };
    }, [session, status]);

    return null; // This component only handles logic, no UI
}