'use client';
import { jsx as k, Fragment as v } from "react/jsx-runtime";
import { useState as S, useMemo as q, useCallback as t, useEffect as Z } from "react";
import { FrankAuth as te } from "@frank-auth/sdk";
import { useAuth as re } from "./use-auth.js";
import "@heroui/react";
import { useConfig as oe } from "../provider/config-provider.js";
const Ie = {
  // Generic CRUD actions
  CREATE: "create",
  READ: "read",
  UPDATE: "update",
  DELETE: "delete",
  // User management actions
  INVITE: "invite",
  REMOVE: "remove",
  SUSPEND: "suspend",
  ACTIVATE: "activate",
  // Admin actions
  MANAGE: "manage",
  CONFIGURE: "configure",
  AUDIT: "audit",
  // Special actions
  TRANSFER: "transfer",
  EXPORT: "export",
  IMPORT: "import"
}, pe = {
  // User resources
  USER: "user",
  USER_PROFILE: "user:profile",
  USER_SESSION: "user:session",
  USER_MFA: "user:mfa",
  // Organization resources
  ORGANIZATION: "organization",
  ORGANIZATION_SETTINGS: "organization:settings",
  ORGANIZATION_MEMBERS: "organization:members",
  ORGANIZATION_INVITATIONS: "organization:invitations",
  ORGANIZATION_BILLING: "organization:billing",
  ORGANIZATION_AUDIT: "organization:audit",
  // Application resources
  APPLICATION: "application",
  APPLICATION_SETTINGS: "application:settings",
  APPLICATION_USERS: "application:users",
  APPLICATION_SESSIONS: "application:sessions",
  // System resources
  SYSTEM: "system",
  SYSTEM_USERS: "system:users",
  SYSTEM_ORGANIZATIONS: "system:organizations",
  SYSTEM_SETTINGS: "system:settings",
  SYSTEM_BILLING: "system:billing",
  SYSTEM_AUDIT: "system:audit"
}, h = {
  SUPER_ADMIN: "system:super_admin",
  ADMIN: "system:admin",
  SUPPORT: "system:support"
}, B = {
  OWNER: "organization:owner",
  ADMIN: "organization:admin",
  MEMBER: "organization:member",
  BILLING: "organization:billing",
  SUPPORT: "organization:support"
};
function w() {
  const { user: a, activeOrganization: s, session: u } = re(), { apiUrl: d, publishableKey: m, userType: A } = oe(), [T, o] = S([]), [y, z] = S([]), [I, E] = S([]), [f, M] = S([]), [l, G] = S(!1), [Y, C] = S(null), [R, D] = S({
    type: "system",
    organizationId: s?.id
  }), P = q(() => u?.accessToken ? new te({
    publishableKey: m,
    apiUrl: d,
    userType: A ?? "end_user"
  }) : null, [m, d, u?.accessToken]), x = t((e) => {
    const n = {
      code: e.code || "UNKNOWN_ERROR",
      message: e.message || "An unknown error occurred",
      details: e.details,
      field: e.field
    };
    C(n);
  }, []), N = t(async () => {
    if (!(!P || !a))
      try {
        G(!0), C(null);
        const [e, n] = await Promise.all([
          P.getUserRoles(a.id),
          P.getUserPermissions(a.id)
        ]);
        E(e), M(n);
        const i = e.map((r) => r.role.name), g = n.map((r) => r.permission.name), L = e.flatMap(
          (r) => r.role.permissions?.map((O) => O.name) || []
        );
        z(i), o([.../* @__PURE__ */ new Set([...g, ...L])]);
      } catch (e) {
        x(e);
      } finally {
        G(!1);
      }
  }, [P, a, x]);
  Z(() => {
    N();
  }, [N]), Z(() => {
    s && D((e) => ({
      ...e,
      organizationId: s.id
    }));
  }, [s]);
  const c = t((e, n) => {
    const i = n || R;
    return f.some((r) => {
      if (r.permission.name !== e) return !1;
      switch (i.type) {
        case "system":
          return r.contextType === "system";
        case "organization":
          return r.contextType === "organization" && r.resourceId === i.organizationId;
        case "application":
          return r.contextType === "application" && r.resourceId === i.applicationId;
        default:
          return !1;
      }
    }) ? !0 : I.some((r) => {
      let O = !1;
      switch (i.type) {
        case "system":
          O = r.contextType === "system";
          break;
        case "organization":
          O = r.contextType === "organization" && r.resourceId === i.organizationId;
          break;
        case "application":
          O = r.contextType === "application" && r.resourceId === i.applicationId;
          break;
      }
      return O && r.role.permissions?.some((ie) => ie.name === e) || !1;
    });
  }, [f, I, R]), p = t((e, n) => {
    const i = n || R;
    return I.some((g) => {
      if (g.role.name !== e) return !1;
      switch (i.type) {
        case "system":
          return g.contextType === "system";
        case "organization":
          return g.contextType === "organization" && g.resourceId === i.organizationId;
        case "application":
          return g.contextType === "application" && g.resourceId === i.applicationId;
        default:
          return !1;
      }
    });
  }, [I, R]), _ = t((e, n) => e.some((i) => c(i, n)), [c]), U = t((e, n) => e.every((i) => c(i, n)), [c]), F = t((e, n, i) => {
    const g = `${n}:${e}`;
    return c(g, i);
  }, [c]), V = t((e, n) => {
    const i = n || s?.id;
    return i ? c(e, {
      type: "organization",
      organizationId: i
    }) : !1;
  }, [c, s]), $ = t((e, n) => c(e, {
    type: "application",
    applicationId: n
  }), [c]), j = t((e) => c(e, { type: "system" }), [c]), W = q(() => p(h.SUPER_ADMIN) || p(h.ADMIN), [p]), b = t((e) => {
    const n = e || s?.id;
    return n ? p(B.OWNER, {
      type: "organization",
      organizationId: n
    }) : !1;
  }, [p, s]), K = t((e) => {
    const n = e || s?.id;
    return n ? p(B.ADMIN, {
      type: "organization",
      organizationId: n
    }) || b(n) : !1;
  }, [p, b, s]), X = t((e) => {
    const n = e || s?.id;
    return n ? I.some(
      (i) => i.contextType === "organization" && i.resourceId === n
    ) : !1;
  }, [I, s]), H = t((e, n) => {
    if (!c(e, n))
      throw new Error(`Permission required: ${e}`);
  }, [c]), J = t((e, n) => {
    if (!p(e, n))
      throw new Error(`Role required: ${e}`);
  }, [p]), Q = t((e, n) => {
    if (!_(e, n))
      throw new Error(`One of these permissions required: ${e.join(", ")}`);
  }, [_]), ee = t((e, n) => {
    if (!U(e, n))
      throw new Error(`All of these permissions required: ${e.join(", ")}`);
  }, [U]), ne = t(async () => {
    await N();
  }, [N]), se = t((e) => {
    D(e);
  }, []);
  return {
    // Permission state
    permissions: T,
    roles: y,
    roleAssignments: I,
    permissionAssignments: f,
    isLoaded: !!a,
    isLoading: l,
    error: Y,
    // Permission checking
    hasPermission: c,
    hasRole: p,
    hasAnyPermission: _,
    hasAllPermissions: U,
    can: F,
    // Context-aware checking
    canInOrganization: V,
    canInApplication: $,
    hasSystemPermission: j,
    // Role checking
    isSystemAdmin: W,
    isOrganizationOwner: b,
    isOrganizationAdmin: K,
    isOrganizationMember: X,
    // Permission management
    refreshPermissions: ne,
    // Convenience methods
    requirePermission: H,
    requireRole: J,
    requireAnyPermission: Q,
    requireAllPermissions: ee,
    // Current context
    currentContext: R,
    setContext: se
  };
}
function de(a) {
  const {
    canInOrganization: s,
    isOrganizationOwner: u,
    isOrganizationAdmin: d,
    isOrganizationMember: m,
    hasRole: A,
    activeOrganization: T
  } = w(), o = a || T?.id;
  return {
    organizationId: o,
    isOwner: u(o),
    isAdmin: d(o),
    isMember: m(o),
    // Common organization permissions
    canManageMembers: s("organization:members:manage", o),
    canInviteMembers: s("organization:members:invite", o),
    canRemoveMembers: s("organization:members:remove", o),
    canManageSettings: s("organization:settings:manage", o),
    canManageBilling: s("organization:billing:manage", o),
    canViewAudit: s("organization:audit:read", o),
    canDeleteOrganization: s("organization:delete", o),
    // Role checking for organization
    hasOrganizationRole: (y) => A(y, {
      type: "organization",
      organizationId: o
    })
  };
}
function Ae() {
  const {
    hasSystemPermission: a,
    isSystemAdmin: s,
    hasRole: u,
    userType: d
  } = w(), m = d === "internal";
  return {
    canAccessSystem: m,
    isSystemAdmin: s,
    // Common system permissions
    canManageUsers: m && a("system:users:manage"),
    canManageOrganizations: m && a("system:organizations:manage"),
    canManageSystem: m && a("system:manage"),
    canViewSystemAudit: m && a("system:audit:read"),
    canManageBilling: m && a("system:billing:manage"),
    // Role checking for system
    hasSystemRole: (A) => u(A, { type: "system" }),
    isSuperAdmin: u(h.SUPER_ADMIN, { type: "system" }),
    isSupport: u(h.SUPPORT, { type: "system" })
  };
}
function Se() {
  const {
    hasPermission: a,
    hasRole: s,
    hasAnyPermission: u,
    hasAllPermissions: d,
    requirePermission: m,
    requireRole: A
  } = w();
  return {
    PermissionGuard: t(({
      permission: o,
      role: y,
      anyPermissions: z,
      allPermissions: I,
      context: E,
      fallback: f = null,
      children: M
    }) => {
      let l = !0;
      return o && (l = l && a(o, E)), y && (l = l && s(y, E)), z && (l = l && u(z, E)), I && (l = l && d(I, E)), l ? /* @__PURE__ */ k(v, { children: M }) : /* @__PURE__ */ k(v, { children: f });
    }, [a, s, u, d]),
    requirePermission: m,
    requireRole: A
  };
}
export {
  B as ORGANIZATION_ROLES,
  Ie as PERMISSION_ACTIONS,
  pe as PERMISSION_RESOURCES,
  h as SYSTEM_ROLES,
  de as useOrganizationPermissions,
  Se as usePermissionGuard,
  w as usePermissions,
  Ae as useSystemPermissions
};
//# sourceMappingURL=use-permissions.js.map
