/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var public_data_surface_default_filter_exports = {};
__export(public_data_surface_default_filter_exports, {
  FLOW_SURFACE_DEFAULT_FILTER_MAX_CANDIDATE_FIELDS: () => FLOW_SURFACE_DEFAULT_FILTER_MAX_CANDIDATE_FIELDS,
  FLOW_SURFACE_DEFAULT_FILTER_MINIMUM_COVERAGE_FIELDS: () => FLOW_SURFACE_DEFAULT_FILTER_MINIMUM_COVERAGE_FIELDS,
  FLOW_SURFACE_DEFAULT_FILTER_REQUIRED_FIELD_COUNT: () => FLOW_SURFACE_DEFAULT_FILTER_REQUIRED_FIELD_COUNT,
  FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPES: () => FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPES,
  FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPE_LABEL: () => FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPE_LABEL,
  assertFlowSurfaceConcreteDefaultFilterItem: () => assertFlowSurfaceConcreteDefaultFilterItem,
  backfillFlowSurfaceDefaultFilterSetting: () => backfillFlowSurfaceDefaultFilterSetting,
  backfillFlowSurfaceFilterActionDefaultFilter: () => backfillFlowSurfaceFilterActionDefaultFilter,
  buildFlowSurfaceDefaultFilterFromCollection: () => buildFlowSurfaceDefaultFilterFromCollection,
  clampFlowSurfaceDefaultFilterToCandidateLimit: () => clampFlowSurfaceDefaultFilterToCandidateLimit,
  isFlowSurfaceDefaultFilterEligibleField: () => isFlowSurfaceDefaultFilterEligibleField,
  isFlowSurfacePublicDataSurfaceBlockType: () => isFlowSurfacePublicDataSurfaceBlockType,
  normalizeFlowSurfacePublicBlockDefaultFilter: () => normalizeFlowSurfacePublicBlockDefaultFilter,
  resolveFlowSurfaceDefaultFilterCandidateFieldNames: () => resolveFlowSurfaceDefaultFilterCandidateFieldNames,
  resolveFlowSurfaceDefaultFilterFieldNames: () => resolveFlowSurfaceDefaultFilterFieldNames,
  resolveFlowSurfaceDefaultFilterMinimumCandidateFieldNames: () => resolveFlowSurfaceDefaultFilterMinimumCandidateFieldNames,
  resolveFlowSurfaceDefaultFilterRequiredFieldCount: () => resolveFlowSurfaceDefaultFilterRequiredFieldCount
});
module.exports = __toCommonJS(public_data_surface_default_filter_exports);
var import_lodash = __toESM(require("lodash"));
var import_errors = require("./errors");
var import_filter_group = require("./filter-group");
var import_service_helpers = require("./service-helpers");
var import_template_reference = require("./template-reference");
const FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPES = /* @__PURE__ */ new Set([
  "table",
  "list",
  "gridCard",
  "calendar",
  "kanban"
]);
const FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPE_LABEL = "table/list/gridCard/calendar/kanban";
const FLOW_SURFACE_DEFAULT_FILTER_MAX_CANDIDATE_FIELDS = 4;
const FLOW_SURFACE_DEFAULT_FILTER_REQUIRED_FIELD_COUNT = 3;
const FLOW_SURFACE_DEFAULT_FILTER_MINIMUM_COVERAGE_FIELDS = FLOW_SURFACE_DEFAULT_FILTER_REQUIRED_FIELD_COUNT;
const FLOW_SURFACE_DEFAULT_FILTER_CANDIDATE_INTERFACES = /* @__PURE__ */ new Set([
  "input",
  "email",
  "url",
  "phone",
  "textarea",
  "select",
  "radioGroup"
]);
const FLOW_SURFACE_DEFAULT_FILTER_EXCLUDED_FIELD_NAMES = /* @__PURE__ */ new Set([
  "id",
  "createdAt",
  "updatedAt",
  "deletedAt",
  "createdBy",
  "updatedBy",
  "deletedBy",
  "created_at",
  "updated_at",
  "deleted_at",
  "created_by",
  "updated_by",
  "deleted_by",
  "sort"
]);
const FLOW_SURFACE_DEFAULT_FILTER_PREFERRED_FIELD_NAMES = [
  "name",
  "title",
  "nickname",
  "username",
  "email",
  "status",
  "phone",
  "mobile",
  "label",
  "code",
  "subject",
  "category",
  "scope",
  "priority",
  "description"
];
function isFlowSurfacePublicDataSurfaceBlockType(blockType) {
  return FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPES.has(String(blockType || "").trim());
}
function resolveFlowSurfaceDefaultFilterMinimumCandidateFieldNames(collection, options = {}) {
  const minimumFields = normalizePositiveInteger(
    options.minimumFields,
    FLOW_SURFACE_DEFAULT_FILTER_MINIMUM_COVERAGE_FIELDS
  );
  const candidateFieldNames = resolveFlowSurfaceDefaultFilterCandidateFieldNames(collection, options);
  return candidateFieldNames.slice(0, Math.min(minimumFields, candidateFieldNames.length));
}
function resolveFlowSurfaceDefaultFilterRequiredFieldCount(collection) {
  if (!collection) {
    return FLOW_SURFACE_DEFAULT_FILTER_REQUIRED_FIELD_COUNT;
  }
  const candidateFieldCount = resolveFlowSurfaceDefaultFilterCandidateFieldNames(collection, {
    maxCandidates: FLOW_SURFACE_DEFAULT_FILTER_MAX_CANDIDATE_FIELDS
  }).length;
  return Math.min(FLOW_SURFACE_DEFAULT_FILTER_REQUIRED_FIELD_COUNT, candidateFieldCount);
}
function resolveFlowSurfaceDefaultFilterCandidateFieldNames(collection, options = {}) {
  const maxCandidates = normalizePositiveInteger(
    options.maxCandidates,
    FLOW_SURFACE_DEFAULT_FILTER_MAX_CANDIDATE_FIELDS
  );
  if (!collection || maxCandidates === 0) {
    return [];
  }
  const availableFields = (0, import_service_helpers.getCollectionFields)(collection).filter(isFlowSurfaceDefaultFilterEligibleField);
  const fieldsByName = /* @__PURE__ */ new Map();
  availableFields.forEach((field) => {
    const fieldName = normalizeText((0, import_service_helpers.getFieldName)(field));
    if (fieldName && !fieldsByName.has(fieldName)) {
      fieldsByName.set(fieldName, field);
    }
  });
  const selectedFieldNames = [];
  const seenFieldNames = /* @__PURE__ */ new Set();
  const pushFieldByName = (value) => {
    if (selectedFieldNames.length >= maxCandidates) {
      return;
    }
    const fieldName = normalizeText(value);
    if (!fieldName || seenFieldNames.has(fieldName) || !fieldsByName.has(fieldName)) {
      return;
    }
    seenFieldNames.add(fieldName);
    selectedFieldNames.push(fieldName);
  };
  pushFieldByName((0, import_service_helpers.getCollectionTitleFieldName)(collection));
  FLOW_SURFACE_DEFAULT_FILTER_PREFERRED_FIELD_NAMES.forEach(pushFieldByName);
  availableFields.forEach((field) => pushFieldByName((0, import_service_helpers.getFieldName)(field)));
  return selectedFieldNames;
}
function buildFlowSurfaceDefaultFilterFromCollection(collection, options = {}) {
  const candidateFieldNames = resolveFlowSurfaceDefaultFilterCandidateFieldNames(collection, options);
  if (!candidateFieldNames.length) {
    return void 0;
  }
  return {
    logic: "$and",
    items: candidateFieldNames.map((fieldName) => ({
      path: fieldName,
      operator: resolveFlowSurfaceDefaultFilterOperator(collection, fieldName)
    }))
  };
}
function clampFlowSurfaceDefaultFilterToCandidateLimit(defaultFilter) {
  return clampFlowSurfaceDefaultFilterGroup(defaultFilter, FLOW_SURFACE_DEFAULT_FILTER_MAX_CANDIDATE_FIELDS).value;
}
function resolveFlowSurfaceDefaultFilterFieldNames(defaultFilter) {
  const fieldNames = [];
  const seen = /* @__PURE__ */ new Set();
  const visit = (value) => {
    if (Array.isArray(value)) {
      value.forEach(visit);
      return;
    }
    if (!import_lodash.default.isPlainObject(value)) {
      return;
    }
    const path = typeof value.path === "string" ? value.path.trim() : "";
    if (path && !seen.has(path)) {
      seen.add(path);
      fieldNames.push(path);
    }
    if (Array.isArray(value.items)) {
      value.items.forEach(visit);
    }
  };
  visit(defaultFilter);
  return fieldNames;
}
function clampFlowSurfaceDefaultFilterGroup(value, remaining) {
  if (remaining <= 0) {
    return {
      value: import_lodash.default.isPlainObject(value) ? {
        ...import_lodash.default.cloneDeep(value),
        items: []
      } : value,
      remaining: 0
    };
  }
  if (!import_lodash.default.isPlainObject(value) || !Array.isArray(value.items)) {
    return {
      value: import_lodash.default.cloneDeep(value),
      remaining
    };
  }
  const nextItems = [];
  let nextRemaining = remaining;
  for (const item of value.items) {
    if (nextRemaining <= 0) {
      break;
    }
    if (import_lodash.default.isPlainObject(item) && Array.isArray(item.items)) {
      const nested = clampFlowSurfaceDefaultFilterGroup(item, nextRemaining);
      if (import_lodash.default.isPlainObject(nested.value) && Array.isArray(nested.value.items) && nested.value.items.length) {
        nextItems.push(nested.value);
      }
      nextRemaining = nested.remaining;
      continue;
    }
    if (import_lodash.default.isPlainObject(item) && typeof item.path === "string" && typeof item.operator === "string") {
      nextItems.push(import_lodash.default.cloneDeep(item));
      nextRemaining -= 1;
      continue;
    }
    nextItems.push(import_lodash.default.cloneDeep(item));
  }
  return {
    value: {
      ...import_lodash.default.cloneDeep(value),
      items: nextItems
    },
    remaining: nextRemaining
  };
}
function normalizeFlowSurfacePublicBlockDefaultFilter(actionName, defaultFilter, options) {
  if (import_lodash.default.isUndefined(defaultFilter)) {
    return void 0;
  }
  const fieldPath = buildFlowSurfaceDefaultFilterFieldPath(actionName, options.path);
  if (!isFlowSurfacePublicDataSurfaceBlockType(options.blockType) || (0, import_template_reference.hasFlowSurfaceTemplateDocument)(options.template)) {
    (0, import_errors.throwBadRequest)(
      `flowSurfaces ${actionName} ${fieldPath} is only supported on direct ${FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPE_LABEL} blocks`
    );
  }
  const normalized = (0, import_filter_group.normalizeFlowSurfaceFilterGroupValue)(
    defaultFilter,
    `flowSurfaces ${actionName} ${fieldPath} expects FilterGroup like ${import_filter_group.FLOW_SURFACE_FILTER_GROUP_EXAMPLE}`,
    { strictDateValues: true }
  );
  return normalized;
}
function assertFlowSurfaceConcreteDefaultFilterItem(actionName, defaultFilter, options = {}) {
  const fieldPath = buildFlowSurfaceDefaultFilterFieldPath(actionName, options.path);
  if (!hasConcreteFlowSurfaceFilterItem(defaultFilter)) {
    (0, import_errors.throwBadRequest)(
      `flowSurfaces ${actionName} ${fieldPath} must include at least one concrete filter item; empty defaultFilter groups such as {}, null, or { logic, items: [] } are not allowed`
    );
  }
}
function buildFlowSurfaceDefaultFilterFieldPath(actionName, path) {
  if (!path) {
    return "defaultFilter";
  }
  const prefix = `flowSurfaces ${actionName} `;
  const normalizedPath = path.startsWith(prefix) ? path.slice(prefix.length) : path;
  return normalizedPath.endsWith(".defaultFilter") ? normalizedPath : `${normalizedPath}.defaultFilter`;
}
function hasConcreteFlowSurfaceFilterItem(filter) {
  if (!import_lodash.default.isPlainObject(filter) || !Array.isArray(filter.items)) {
    return false;
  }
  return filter.items.some((item) => {
    if (import_lodash.default.isPlainObject(item) && "logic" in item && "items" in item) {
      return hasConcreteFlowSurfaceFilterItem(item);
    }
    return import_lodash.default.isPlainObject(item) && typeof item.path === "string" && typeof item.operator === "string";
  });
}
function backfillFlowSurfaceDefaultFilterSetting(settings, defaultFilter) {
  if (import_lodash.default.isUndefined(defaultFilter)) {
    return settings;
  }
  const defaults = {
    defaultFilter: import_lodash.default.cloneDeep(defaultFilter)
  };
  if (import_lodash.default.isUndefined(settings)) {
    return defaults;
  }
  if (!import_lodash.default.isPlainObject(settings)) {
    return settings;
  }
  if (Object.prototype.hasOwnProperty.call(settings, "defaultFilter")) {
    return settings;
  }
  return {
    ...defaults,
    ...import_lodash.default.cloneDeep(settings)
  };
}
function backfillFlowSurfaceFilterActionDefaultFilter(actions, defaultFilter) {
  if (import_lodash.default.isUndefined(defaultFilter)) {
    return actions;
  }
  return actions.map((action) => {
    if (String((action == null ? void 0 : action.type) || "").trim() !== "filter") {
      return action;
    }
    const settings = backfillFlowSurfaceDefaultFilterSetting(action.settings, defaultFilter);
    if (settings === action.settings) {
      return action;
    }
    return {
      ...action,
      settings
    };
  });
}
function isFlowSurfaceDefaultFilterEligibleField(field) {
  var _a;
  const fieldName = normalizeText((0, import_service_helpers.getFieldName)(field));
  const fieldInterface = normalizeText((0, import_service_helpers.getFieldInterface)(field));
  if (!fieldName || !fieldInterface) {
    return false;
  }
  if (FLOW_SURFACE_DEFAULT_FILTER_EXCLUDED_FIELD_NAMES.has(fieldName)) {
    return false;
  }
  if (!FLOW_SURFACE_DEFAULT_FILTER_CANDIDATE_INTERFACES.has(fieldInterface)) {
    return false;
  }
  if ((field == null ? void 0 : field.hidden) === true || ((_a = field == null ? void 0 : field.options) == null ? void 0 : _a.hidden) === true) {
    return false;
  }
  if ((0, import_service_helpers.getFieldFilterable)(field) === false) {
    return false;
  }
  return !(0, import_service_helpers.isAssociationField)(field);
}
function resolveFlowSurfaceDefaultFilterOperator(collection, fieldName) {
  const field = (0, import_service_helpers.getCollectionFields)(collection).find(
    (candidate) => normalizeText((0, import_service_helpers.getFieldName)(candidate)) === fieldName
  );
  const fieldInterface = normalizeText((0, import_service_helpers.getFieldInterface)(field));
  return fieldInterface === "select" || fieldInterface === "radioGroup" ? "$eq" : "$includes";
}
function normalizeText(value) {
  return typeof value === "string" || typeof value === "number" ? String(value).replace(/\s+/g, " ").trim() : "";
}
function normalizePositiveInteger(value, fallback) {
  const num = typeof value === "number" && Number.isFinite(value) ? value : fallback;
  return Math.max(0, Math.trunc(num));
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  FLOW_SURFACE_DEFAULT_FILTER_MAX_CANDIDATE_FIELDS,
  FLOW_SURFACE_DEFAULT_FILTER_MINIMUM_COVERAGE_FIELDS,
  FLOW_SURFACE_DEFAULT_FILTER_REQUIRED_FIELD_COUNT,
  FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPES,
  FLOW_SURFACE_PUBLIC_DATA_SURFACE_BLOCK_TYPE_LABEL,
  assertFlowSurfaceConcreteDefaultFilterItem,
  backfillFlowSurfaceDefaultFilterSetting,
  backfillFlowSurfaceFilterActionDefaultFilter,
  buildFlowSurfaceDefaultFilterFromCollection,
  clampFlowSurfaceDefaultFilterToCandidateLimit,
  isFlowSurfaceDefaultFilterEligibleField,
  isFlowSurfacePublicDataSurfaceBlockType,
  normalizeFlowSurfacePublicBlockDefaultFilter,
  resolveFlowSurfaceDefaultFilterCandidateFieldNames,
  resolveFlowSurfaceDefaultFilterFieldNames,
  resolveFlowSurfaceDefaultFilterMinimumCandidateFieldNames,
  resolveFlowSurfaceDefaultFilterRequiredFieldCount
});
