"use client";

import { FC, PropsWithChildren, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";

export const ZammadLoginProvider: FC<PropsWithChildren> = ({ children }) => {
  const { data: session, status, update } = useSession();
  const router = useRouter();

  useEffect(() => {
    const checkSession = async () => {
      if (status === "authenticated") {
        const response = await fetch("/api/v1/users/me", {
          method: "GET",
        });

        if (response.status !== 200) {
          window.location.href = "/auth/sso";
        }
      }
    };

    const interval = setInterval(checkSession, 15000);

    return () => clearInterval(interval);
  }, [session, status, update, router]);

  return children;
};
