"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",
          headers: {
            "X-Browser-Fingerprint": `${session.expires}`,
          },
        });

        if (response.status !== 200) {
          window.location.href = "/zammad/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;
};
