import { joinURL as o } from "ufo";
import { getMaster as l, getFederatedEnabled as p } from "@arcblock/ux/lib/Util/federated";
import { createAxios as g, sleep as w } from "../../utils.js";
import { BLOCKLET_SERVICE_PATH_PREFIX as i } from "../../constant.js";
const c = g();
async function y() {
  const t = o(i, "/api/federated/loginMaster"), { data: r } = await c.post(t);
  return r;
}
async function h({ mode: t, refreshToken: r = "", blocklet: a }) {
  const s = l(a);
  return new Promise((n) => {
    if (!["login", "logout"].includes(t)) {
      n();
      return;
    }
    const e = document.createElement("iframe");
    e.style.display = "none", e.onload = async () => {
      await w(500), document.body.removeChild(e), n();
    }, e.src = o(
      s.appUrl,
      i,
      `functional/federated?mode=${t}&refreshToken=${r}`
    ), document.body.appendChild(e);
  });
}
async function C(t = {}, { fetchToken: r = !0, blocklet: a } = {}) {
  if (!p())
    return console.warn("Federated not enabled"), null;
  let n, e;
  r && ({ sessionToken: n, refreshToken: e } = await y());
  const f = l(a), m = o(f.appUrl, i, "/api/federated/login"), d = { withCredentials: !0 };
  n && (d.headers = {
    Authorization: `Bearer ${n}`
  });
  const { data: u } = await c.post(m, t, d);
  return e && await h({ mode: "login", refreshToken: e, blocklet: a }), u;
}
export {
  C as loginFederatedMaster,
  h as mountFederatedIframe
};
