import { CustomFieldEntityConfig } from "../data/entities.js";
const DEFAULT_CONFIG = {
  fieldsets: [],
  singleFieldsetPerRecord: true
};
function normalizeCode(input) {
  if (typeof input !== "string") return "";
  const trimmed = input.trim();
  if (!trimmed) return "";
  return trimmed;
}
function normalizeFieldset(raw) {
  if (!raw || typeof raw !== "object") return null;
  const code = normalizeCode(raw.code);
  const label = typeof raw.label === "string" && raw.label.trim().length ? raw.label.trim() : "";
  if (!code || !label) return null;
  const normalized = {
    code,
    label
  };
  if (typeof raw.icon === "string" && raw.icon.trim()) normalized.icon = raw.icon.trim();
  if (typeof raw.description === "string" && raw.description.trim()) normalized.description = raw.description.trim();
  if (Array.isArray(raw.groups) && raw.groups.length) {
    const groups = [];
    const seen = /* @__PURE__ */ new Set();
    for (const entry of raw.groups) {
      if (!entry || typeof entry !== "object") continue;
      const groupCode = normalizeCode(entry.code);
      if (!groupCode || seen.has(groupCode)) continue;
      seen.add(groupCode);
      groups.push({
        code: groupCode,
        title: typeof entry.title === "string" && entry.title.trim().length ? entry.title.trim() : void 0,
        hint: typeof entry.hint === "string" && entry.hint.trim().length ? entry.hint.trim() : void 0
      });
    }
    if (groups.length) normalized.groups = groups;
  }
  return normalized;
}
function normalizeConfig(raw) {
  if (!raw || typeof raw !== "object") return DEFAULT_CONFIG;
  const cfg = raw.configJson ?? raw;
  const fieldsetsRaw = Array.isArray(cfg?.fieldsets) ? cfg.fieldsets : [];
  const normalizedFieldsets = fieldsetsRaw.map((entry) => normalizeFieldset(entry)).filter((entry) => Boolean(entry));
  const seenCodes = /* @__PURE__ */ new Set();
  const fieldsets = [];
  for (const entry of normalizedFieldsets) {
    if (seenCodes.has(entry.code)) continue;
    seenCodes.add(entry.code);
    fieldsets.push(entry);
  }
  const singleFieldsetPerRecord = typeof cfg?.singleFieldsetPerRecord === "boolean" ? cfg.singleFieldsetPerRecord : true;
  return {
    fieldsets,
    singleFieldsetPerRecord
  };
}
async function loadEntityFieldsetConfigs(em, options) {
  const map = /* @__PURE__ */ new Map();
  if (!options.entityIds.length) return map;
  const where = {
    entityId: { $in: options.entityIds },
    deletedAt: null,
    isActive: true
  };
  const tenantMatch = options.tenantId ?? void 0;
  where.$and = [
    { $or: [{ tenantId: tenantMatch }, { tenantId: null }] }
  ];
  if (options.mode === "manage") {
    const orgMatch = options.organizationId ?? void 0;
    where.$and.push({ $or: [{ organizationId: orgMatch }, { organizationId: null }] });
  }
  const rows = await em.find(CustomFieldEntityConfig, where);
  const bucket = /* @__PURE__ */ new Map();
  for (const row of rows) {
    const entityId = String(row.entityId);
    const list = bucket.get(entityId) ?? [];
    list.push(row);
    bucket.set(entityId, list);
  }
  const scopeScore = (row) => {
    let score = 0;
    if (row.tenantId) {
      score += row.tenantId === options.tenantId ? 2 : 0;
    } else {
      score += 1;
    }
    if (row.organizationId) {
      score += row.organizationId === options.organizationId ? 1 : -1;
    }
    return score;
  };
  for (const entityId of options.entityIds) {
    const list = bucket.get(entityId) ?? [];
    if (!list.length) continue;
    list.sort((a, b) => {
      const diff = scopeScore(b) - scopeScore(a);
      if (diff !== 0) return diff;
      const timeA = a.updatedAt instanceof Date ? a.updatedAt.getTime() : new Date(a.updatedAt).getTime();
      const timeB = b.updatedAt instanceof Date ? b.updatedAt.getTime() : new Date(b.updatedAt).getTime();
      return timeB - timeA;
    });
    const winner = list[0];
    map.set(entityId, normalizeConfig(winner.configJson ?? {}));
  }
  return map;
}
function mergeEntityFieldsetConfig(current, patch) {
  const base = current ?? DEFAULT_CONFIG;
  return {
    fieldsets: Array.isArray(patch.fieldsets) ? patch.fieldsets : base.fieldsets,
    singleFieldsetPerRecord: patch.singleFieldsetPerRecord !== void 0 ? patch.singleFieldsetPerRecord : base.singleFieldsetPerRecord
  };
}
function normalizeEntityFieldsetConfig(raw) {
  if (!raw) return DEFAULT_CONFIG;
  return normalizeConfig(raw);
}
export {
  loadEntityFieldsetConfigs,
  mergeEntityFieldsetConfig,
  normalizeEntityFieldsetConfig
};
//# sourceMappingURL=fieldsets.js.map
