import { joinURL as y } from "ufo";
import { createAxios as m } from "../utils.js";
async function g(o, { authServicePrefix: s, serviceHost: i }) {
  if (!o)
    throw new Error("Refresh token not found");
  const u = m({
    baseURL: i,
    timeout: 10 * 1e3,
    secure: !0,
    headers: {
      authorization: `Bearer ${encodeURIComponent(o)}`
    }
  }), { data: a } = await u.post(y(s, "/refreshSession"));
  return a;
}
function v({
  refreshTokenStorage: o,
  sessionTokenStorage: s,
  serviceHost: i,
  authServicePrefix: u,
  onRefreshTokenError: a,
  onRefreshTokenSuccess: f
}, k = {}) {
  let n = null;
  const c = m({
    baseURL: i,
    timeout: 30 * 1e3,
    ...k
  }), { getToken: h, setToken: p, removeToken: T } = s, { getToken: R, setToken: l, removeToken: d } = o;
  return c.interceptors.request.use(
    async (e) => {
      if (s.engine === "ls") {
        const t = h();
        t && (e.headers.authorization = `Bearer ${encodeURIComponent(t)}`);
      }
      return n && await n, e;
    },
    (e) => Promise.reject(e)
  ), c.interceptors.response.use(
    (e) => e,
    async (e) => {
      const t = e.config;
      if (!t)
        return Promise.reject(e);
      if (t.headers = { ...t?.headers }, e?.response?.status === 401 && !t._retry) {
        t._retry = !0, n || (n = g(R(), { serviceHost: i, authServicePrefix: u }));
        try {
          const r = await n;
          return p(r.nextToken), l(r.nextRefreshToken), typeof f == "function" && f(r), c(t);
        } catch (r) {
          return T(), d(), typeof a == "function" && a(), Promise.reject(r);
        } finally {
          n = null;
        }
      }
      return Promise.reject(e);
    }
  ), c;
}
export {
  v as default
};
