// authManager.js
import { store } from "../index";
import { setToken, setLogout } from "@/state";

let refreshPromise = null;

export const refreshToken = () => {
  if (refreshPromise) return refreshPromise;

  refreshPromise = fetch(`${import.meta.env.VITE_BASE_URL}/auth/refresh`, {
    method: "POST",
    credentials: "include",
  })
    .then(async (res) => {
      if (!res.ok) throw new Error("refresh failed");
      return res.json();
    })
    .then((data) => {
      store.dispatch(setToken(data.token));
      return data.token;
    })
    .catch(() => {
      store.dispatch(setLogout());
      window.location.href = "/";
    })
    .finally(() => {
      refreshPromise = null;
    });

  return refreshPromise;
};
