"use client";

import { FC, PropsWithChildren, 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();

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

        if (response.status !== 200 && !!router) {
          console.log("redirecting");
          window.location.href = "/auth/sso";
        } else {
          const token = response.headers.get("CSRF-Token");
          update({ zammadCsrfToken: token });
        }
      }
    };

    const interval = setInterval(checkSession, 15000);

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

  return children;
};
