import { flatTree as M } from "@das-fed/utils/common-tools";
import { projectNextTick as y } from "@das-fed/utils/nextTiken";
import { vAuth as T } from "@das-fed/utils/directive/auth";
import { portal as U, superadminPortal as w, enterpriseright as v } from "@das-fed/utils/api-services/modules";
const B = U.get("/appcategory"), C = w.get("/appcategory"), L = v.get("/permissionset/user-portal-menu"), P = w.get("/user-menu"), G = () => {
  const d = async (r, i = "enterpriseadmin") => {
    let t = null, s = {};
    await y(), i === "superadmin" ? t = C().run : (s = { userType: 1 }, t = B().run);
    const [o, l] = await t(s);
    if (o || !l || !l.length) return null;
    const p = l.map((e) => e.apps).flat();
    return r ? p.find((e) => e.code === r) : p;
  }, g = async (r, i, t, s = "enterpriseadmin", o = !1) => {
    var h;
    await y();
    let l = null, p = {
      code: r,
      showBtn: !0
    };
    s === "superadmin" ? l = P().run : (p.userType = 1, l = L().run);
    const [a, e] = await l(p);
    if (a || !e || !e.length)
      return i || t ? void 0 : [];
    if (!i && !t) return e;
    const m = e != null && e.length ? o ? e : e.filter((n) => n.routeUrl) : [], f = e != null && e.length ? e.filter((n) => !n.routeUrl && n.children).map((n) => n.children).flat() : [], u = [...m, ...f];
    let c;
    if (i)
      c = u.find((n) => n.code === i || n.originalCode === i);
    else if (t) {
      const n = t.replace(((h = u[0]) == null ? void 0 : h.applicationPath) ?? "", "").replace(/\/\//g, "/");
      c = u.find((A) => A.routeUrl && A.routeUrl === n);
    }
    return c;
  };
  return {
    getApplication: d,
    getMenu: g,
    getAuth: async (r, i = "enterpriseadmin") => {
      var f;
      const t = (r == null ? void 0 : r.applicationCode) ?? "", s = (r == null ? void 0 : r.menuCode) ?? "", o = (r == null ? void 0 : r.code) ?? "";
      if (JSON.parse(sessionStorage.getItem("permission-btn") || "{}")[s]) return T(null, { applicationCode: t, menuCode: s, code: o });
      if (!await d(t, i)) return !1;
      const a = await g(t, s, i);
      return !a || !(a != null && a.children) || !((f = a.children) != null && f.length) ? !1 : !!M(a.children).find((u) => {
        let c = (u == null ? void 0 : u.originalCode) ?? u.code;
        return c.includes(s + ".") && (c = c.replace(s + ".", "").replaceAll(".", "-")), c === o;
      });
    }
  };
};
export {
  G as useGetAuth
};
