import { DashboardRoleWidgets, DashboardUserWidgets } from "../data/entities.js";
import { UserRole } from "@open-mercato/core/modules/auth/data/entities";
import { hasAllFeatures as userHasAllFeatures } from "@open-mercato/shared/security/features";
import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
function specificity(record) {
  let score = 0;
  if (record.tenantId) score += 1;
  if (record.organizationId) score += 2;
  return score;
}
async function resolveAllowedWidgetIds(em, ctx, widgets) {
  const allWidgetIds = widgets.map((w) => w.metadata.id);
  const userRecord = await em.findOne(DashboardUserWidgets, {
    userId: ctx.userId,
    tenantId: ctx.tenantId,
    organizationId: ctx.organizationId,
    deletedAt: null
  });
  let allowedByUser = null;
  if (userRecord) {
    if (userRecord.mode === "override") {
      allowedByUser = new Set(userRecord.widgetIdsJson.filter((id) => allWidgetIds.includes(id)));
    } else {
      allowedByUser = null;
    }
  }
  let baseSet;
  if (allowedByUser) {
    baseSet = allowedByUser;
  } else {
    const userRoles = await findWithDecryption(
      em,
      UserRole,
      { user: ctx.userId, deletedAt: null },
      { populate: ["role"] },
      { tenantId: ctx.tenantId, organizationId: ctx.organizationId }
    );
    const roleRecords = await em.find(DashboardRoleWidgets, {
      roleId: { $in: userRoles.map((ur) => String(ur.role?.id || ur.role)) },
      deletedAt: null
    });
    const byRole = /* @__PURE__ */ new Map();
    for (const record of roleRecords) {
      const role = String(record.roleId);
      if (record.tenantId && ctx.tenantId && record.tenantId !== ctx.tenantId) continue;
      if (record.tenantId && !ctx.tenantId) continue;
      if (record.organizationId && ctx.organizationId && record.organizationId !== ctx.organizationId) continue;
      if (record.organizationId && !ctx.organizationId) continue;
      const current = byRole.get(role);
      if (!current || specificity(record) > specificity(current)) {
        byRole.set(role, record);
      }
    }
    const allowedByRole = /* @__PURE__ */ new Set();
    for (const record of byRole.values()) {
      for (const id of record.widgetIdsJson) {
        if (allWidgetIds.includes(id)) allowedByRole.add(id);
      }
    }
    baseSet = allowedByRole.size > 0 ? allowedByRole : new Set(allWidgetIds);
  }
  if (baseSet.size === 0) return [];
  const filtered = widgets.filter((widget) => {
    if (!baseSet.has(widget.metadata.id)) return false;
    if (ctx.isSuperAdmin) return true;
    return userHasAllFeatures(ctx.features, widget.metadata.features ?? []);
  });
  return filtered.map((widget) => widget.metadata.id);
}
export {
  resolveAllowedWidgetIds
};
//# sourceMappingURL=access.js.map
