import { useCreation as i, useMemoizedFn as R, useReactive as L, useRequest as T } from "ahooks";
import { joinURL as d } from "ufo";
import k from "lodash/pick";
import D from "lodash/unionBy";
import E from "lodash/sortBy";
import x from "@arcblock/ux/lib/Toast";
import { BLOCKLET_SERVICE_PATH_PREFIX as A } from "../../constant.js";
import { createAxios as B, logger as c } from "../../utils.js";
const p = d(A, "/api/user-session");
function M({
  appPid: m,
  sourceAppPid: f,
  loginAppPid: g,
  autoFetch: y = !0,
  baseUrl: o = "/",
  fetchAll: I = !1
} = {}) {
  const u = i(() => B(
    {
      baseURL: d(o, p)
    },
    { lazy: !0, lazyTime: 500 }
  ), [o]), S = R(async () => {
    if (!window.blocklet)
      return [];
    let r = [];
    try {
      ({ data: r = [] } = await u.get(""));
    } catch (e) {
      c.error("Failed to get user-sessions", e);
    }
    return r.filter((e) => I ? !0 : !e.appUrl).map((e) => ({
      appUrl: o,
      ...e
    }));
  }), s = L({
    loaded: !1,
    loadingId: null
  }), t = T(S, {
    manual: !y,
    onFinally() {
      s.loaded = !0;
    },
    refreshDeps: [o]
  }), w = async (r) => {
    const a = k(r, ["userDid", "visitorId", "passportId", "id"]);
    try {
      s.loadingId = r.id;
      const { data: e } = await u.post(
        "login",
        { ...a, appPid: g },
        {
          baseURL: d(r.appUrl || "/", p)
        }
      );
      return e;
    } catch (e) {
      const h = e.response ? e.response?.data?.error || e.response?.data : e.message;
      throw x.error(h), c.error("Quick login error", e), e;
    } finally {
      s.loadingId = null;
    }
  }, l = i(() => t.data ? t.data.filter((r) => r.status !== "expired") : [], [t.data]), n = i(() => {
    const r = (/* @__PURE__ */ new Date()).getTime(), a = E(l, (e) => r - new Date(e.updatedAt).getTime());
    return D(
      a,
      (e) => [
        e.userDid
        // 暂不以用户角色来做去重的因子
        // x.user.role
      ].join("_")
    );
  }, [l, f, m]), U = i(() => !!(n && n.length > 0), [n]);
  return {
    loadingId: s.loadingId,
    userSessions: n,
    quickLoginEnabled: U,
    loginUserSession: w,
    loading: t.loading,
    loaded: t.loaded,
    refresh: t.refreshAsync
  };
}
export {
  M as default
};
