"use client";

import { apiInstance } from "@/shared/config/apiConfig";
import { AxiosError } from "axios";
import { signOut, useSession } from "next-auth/react";
import { useEffect } from "react";

const AuthGuard = ({ children }: { children: React.ReactNode }) => {
  const session = useSession();
  const verifyToken = async () => {
    try {
      const data = {
        token: session.data?.access_token,
      };
      await apiInstance.post("/token/verify/", data);
    } catch (error: unknown) {
      if (error instanceof AxiosError) {
        if (error.response?.data.code === "token_not_valid") {
          signOut({
            callbackUrl: "/",
          });
        }
      }
    }
  };

  useEffect(() => {
    if (session.status === "loading") return;

    verifyToken();
  }, [session.status]);
  return <>{children}</>;
};

export default AuthGuard;
