"use client";

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

export const CSRFProvider: FC<PropsWithChildren> = ({ children }) => {
  const { data: session, status, update } = useSession();
  const router = useRouter();
  const [redirectCount, setRedirectCount] = useState(0);

  useEffect(() => {
    const interval = setInterval(async () => {
      console.log("Checking session status...");
      console.log(status);
      if (status === "authenticated") {
        const response = await fetch("/api/v1/users/me");
        console.log(response.ok);
        console.log(!!router);
        if (!response.ok && !!router) {
          console.log("redirecting");
          setRedirectCount(redirectCount + 1);
          router.push("/setup");
        } else {
          setRedirectCount(0);
          const token = response.headers.get("CSRF-Token");
          update({ csrfToken: token });
        }
      }
    }, 15000);

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

  return children;
};
