/**
 * 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 field_type_resolver_exports = {};
__export(field_type_resolver_exports, {
  FLOW_SURFACE_INTERNAL_FIELD_KEYS: () => FLOW_SURFACE_INTERNAL_FIELD_KEYS,
  FLOW_SURFACE_PUBLIC_FIELD_TYPE_SET: () => FLOW_SURFACE_PUBLIC_FIELD_TYPE_SET,
  FLOW_SURFACE_PUBLIC_RELATION_FIELD_TYPES: () => FLOW_SURFACE_PUBLIC_RELATION_FIELD_TYPES,
  FLOW_SURFACE_RESERVED_RELATION_FIELD_TYPES: () => FLOW_SURFACE_RESERVED_RELATION_FIELD_TYPES,
  assertNoInternalFieldKeys: () => assertNoInternalFieldKeys,
  getPublicFieldTypeForUse: () => getPublicFieldTypeForUse,
  normalizePublicFieldNameList: () => normalizePublicFieldNameList,
  normalizePublicFieldType: () => normalizePublicFieldType,
  resolveRelationFieldType: () => resolveRelationFieldType,
  usesNestedRelationFields: () => usesNestedRelationFields
});
module.exports = __toCommonJS(field_type_resolver_exports);
var import_lodash = __toESM(require("lodash"));
var import_errors = require("./errors");
var import_association_interfaces = require("./association-interfaces");
var import_field_semantics = require("./field-semantics");
var import_service_helpers = require("./service-helpers");
var import_association_title_field = require("./association-title-field");
const FLOW_SURFACE_PUBLIC_RELATION_FIELD_TYPES = [
  "text",
  "select",
  "picker",
  "subForm",
  "subFormList",
  "subDetails",
  "subDetailsList",
  "subTable",
  "popupSubTable"
];
const FLOW_SURFACE_RESERVED_RELATION_FIELD_TYPES = ["cascade", "upload", "preview"];
const FLOW_SURFACE_PUBLIC_FIELD_TYPE_SET = /* @__PURE__ */ new Set([
  ...FLOW_SURFACE_PUBLIC_RELATION_FIELD_TYPES,
  ...FLOW_SURFACE_RESERVED_RELATION_FIELD_TYPES
]);
const FLOW_SURFACE_INTERNAL_FIELD_KEYS = [
  "fieldComponent",
  "fieldModel",
  "componentFields",
  "use",
  "fieldUse",
  "subModels",
  "props",
  "stepParams"
];
const FIELD_USE_TO_PUBLIC_FIELD_TYPE = {
  DisplayTextFieldModel: "text",
  RecordSelectFieldModel: "select",
  RecordPickerFieldModel: "picker",
  SubFormFieldModel: "subForm",
  SubFormListFieldModel: "subFormList",
  DisplaySubItemFieldModel: "subDetails",
  DisplaySubListFieldModel: "subDetailsList",
  DisplaySubTableFieldModel: "subTable",
  SubTableFieldModel: "subTable",
  PopupSubTableFieldModel: "popupSubTable"
};
const FIELD_TYPES_WITH_FIELDS = /* @__PURE__ */ new Set([
  "picker",
  "subForm",
  "subFormList",
  "subDetails",
  "subDetailsList",
  "subTable",
  "popupSubTable"
]);
const FIELD_TYPES_WITH_TABLE_PROPS = /* @__PURE__ */ new Set(["subTable", "popupSubTable"]);
function assertNoInternalFieldKeys(input, context) {
  if (!import_lodash.default.isPlainObject(input)) {
    return;
  }
  const forbidden = FLOW_SURFACE_INTERNAL_FIELD_KEYS.filter((key) => Object.prototype.hasOwnProperty.call(input, key));
  if (forbidden.length) {
    (0, import_errors.throwBadRequest)(`${context} does not accept internal field keys: ${forbidden.join(", ")}`);
  }
}
function normalizePublicFieldType(value, context) {
  if (import_lodash.default.isUndefined(value) || import_lodash.default.isNull(value) || value === "") {
    return void 0;
  }
  const normalized = String(value || "").trim();
  if (!normalized) {
    return void 0;
  }
  if (FLOW_SURFACE_RESERVED_RELATION_FIELD_TYPES.includes(normalized)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${context} fieldType '${normalized}' is reserved for plugin-specific field types`);
  }
  if (!FLOW_SURFACE_PUBLIC_RELATION_FIELD_TYPES.includes(normalized)) {
    (0, import_errors.throwBadRequest)(
      `flowSurfaces ${context} fieldType '${normalized}' is not supported; supported fieldTypes: ${FLOW_SURFACE_PUBLIC_RELATION_FIELD_TYPES.join(
        ", "
      )}`
    );
  }
  return normalized;
}
function normalizePublicFieldNameList(value, context) {
  if (import_lodash.default.isUndefined(value)) {
    return void 0;
  }
  if (!Array.isArray(value)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${context} must be an array of field names`);
  }
  return value.map((item, index) => {
    const normalized = String(item || "").trim();
    if (!normalized) {
      (0, import_errors.throwBadRequest)(`flowSurfaces ${context}[${index + 1}] cannot be empty`);
    }
    return normalized;
  });
}
function getPublicFieldTypeForUse(use) {
  return FIELD_USE_TO_PUBLIC_FIELD_TYPE[String(use || "").trim()];
}
function getAssociationCardinality(field) {
  const fieldInterface = String((0, import_service_helpers.getFieldInterface)(field) || "").trim();
  if (import_association_interfaces.SINGLE_VALUE_ASSOCIATION_INTERFACES.has(fieldInterface)) {
    return "single";
  }
  if (import_association_interfaces.MULTI_VALUE_ASSOCIATION_INTERFACES.has(fieldInterface)) {
    return "multi";
  }
  return null;
}
function pickCollectionFallbackFieldName(collection, titleFieldErrorOptions = {}) {
  var _a;
  const safeTitleFieldName = (_a = (0, import_association_title_field.resolveCollectionSafeTitleField)(collection, titleFieldErrorOptions)) == null ? void 0 : _a.fieldName;
  if (safeTitleFieldName && (0, import_service_helpers.resolveFieldFromCollection)(collection, safeTitleFieldName)) {
    return safeTitleFieldName;
  }
  const primaryField = (0, import_service_helpers.getCollectionFields)(collection).find(
    (field) => {
      var _a2;
      return !!(field == null ? void 0 : field.primaryKey) || !!((_a2 = field == null ? void 0 : field.options) == null ? void 0 : _a2.primaryKey);
    }
  );
  return (0, import_service_helpers.getFieldName)(primaryField) || "id";
}
function assertTargetFieldNamesExist(targetCollection, fields, context) {
  fields.forEach((fieldName) => {
    if (!(0, import_service_helpers.resolveFieldFromCollection)(targetCollection, fieldName)) {
      (0, import_errors.throwBadRequest)(`flowSurfaces ${context} field '${fieldName}' does not exist on relation target collection`);
    }
  });
}
function resolveRelationFieldType(input) {
  const fieldType = normalizePublicFieldType(input.fieldType, input.context);
  if (!fieldType) {
    return void 0;
  }
  if (!(0, import_service_helpers.isAssociationField)(input.field)) {
    throw new import_errors.FlowSurfaceBadRequestError("flowSurfaces fieldType is only supported for relation fields");
  }
  const targetCollection = (0, import_service_helpers.resolveFieldTargetCollection)(
    input.field,
    input.dataSourceKey || "main",
    input.getCollection
  );
  if (!targetCollection) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType '${fieldType}' cannot resolve relation target collection`);
  }
  const cardinality = getAssociationCardinality(input.field);
  if (!cardinality) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType '${fieldType}' is not supported for this relation field`);
  }
  const containerKind = (0, import_field_semantics.normalizeFieldContainerKind)(input.containerUse);
  let fieldUse;
  switch (fieldType) {
    case "text":
      fieldUse = containerKind === "form" ? "RecordSelectFieldModel" : "DisplayTextFieldModel";
      break;
    case "select":
      fieldUse = "RecordSelectFieldModel";
      break;
    case "picker":
      fieldUse = "RecordPickerFieldModel";
      break;
    case "subForm":
      if (cardinality !== "single") {
        (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType 'subForm' only supports single relation fields`);
      }
      fieldUse = "SubFormFieldModel";
      break;
    case "subFormList":
      if (cardinality !== "multi") {
        (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType 'subFormList' only supports multi relation fields`);
      }
      fieldUse = "SubFormListFieldModel";
      break;
    case "subDetails":
      if (cardinality !== "single") {
        (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType 'subDetails' only supports single relation fields`);
      }
      fieldUse = "DisplaySubItemFieldModel";
      break;
    case "subDetailsList":
      if (cardinality !== "multi") {
        (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType 'subDetailsList' only supports multi relation fields`);
      }
      fieldUse = "DisplaySubListFieldModel";
      break;
    case "subTable":
      if (cardinality !== "multi") {
        (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType 'subTable' only supports multi relation fields`);
      }
      fieldUse = containerKind === "form" ? "SubTableFieldModel" : "DisplaySubTableFieldModel";
      break;
    case "popupSubTable":
      if (cardinality !== "multi") {
        (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType 'popupSubTable' only supports multi relation fields`);
      }
      fieldUse = "PopupSubTableFieldModel";
      break;
  }
  const explicitFields = normalizePublicFieldNameList(input.fields, `${input.context}.fields`);
  if (explicitFields && !FIELD_TYPES_WITH_FIELDS.has(fieldType)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType '${fieldType}' does not support fields`);
  }
  if ((!import_lodash.default.isUndefined(input.openMode) || !import_lodash.default.isUndefined(input.popupSize)) && fieldType !== "picker") {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType '${fieldType}' does not support openMode or popupSize`);
  }
  if ((!import_lodash.default.isUndefined(input.pageSize) || !import_lodash.default.isUndefined(input.showIndex)) && !FIELD_TYPES_WITH_TABLE_PROPS.has(fieldType)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${input.context} fieldType '${fieldType}' does not support pageSize or showIndex`);
  }
  const baseTitleFieldErrorOptions = {
    action: input.actionName || input.context,
    path: input.titleFieldPath,
    fieldPath: input.fieldPath,
    targetCollection
  };
  const shouldApplyDefaults = input.applyDefaults !== false;
  const defaultTargetField = shouldApplyDefaults ? pickCollectionFallbackFieldName(targetCollection, baseTitleFieldErrorOptions) : void 0;
  const fields = explicitFields ?? (shouldApplyDefaults && (usesNestedRelationFields(fieldUse) || fieldType === "picker") ? [defaultTargetField] : void 0);
  const selectorFields = ["picker", "popupSubTable"].includes(fieldType) ? fields : void 0;
  const titleField = import_lodash.default.isUndefined(input.titleField) ? defaultTargetField : String(input.titleField || "").trim() || void 0;
  const titleFieldErrorOptions = {
    ...baseTitleFieldErrorOptions,
    titleField
  };
  if (titleField) {
    (0, import_association_title_field.assertFlowSurfaceTitleFieldIsNotId)(titleField, titleFieldErrorOptions);
  }
  if (fields == null ? void 0 : fields.length) {
    assertTargetFieldNamesExist(targetCollection, fields, `${input.context}.fields`);
  }
  if (titleField) {
    (0, import_association_title_field.assertCollectionTitleFieldExists)(targetCollection, titleField, titleFieldErrorOptions);
  }
  return {
    fieldType,
    fieldUse,
    cardinality,
    targetCollection,
    fields,
    selectorFields,
    titleField,
    openMode: input.openMode,
    popupSize: input.popupSize,
    pageSize: input.pageSize,
    showIndex: input.showIndex
  };
}
function usesNestedRelationFields(fieldUse) {
  return [
    "SubTableFieldModel",
    "PopupSubTableFieldModel",
    "DisplaySubTableFieldModel",
    "SubFormFieldModel",
    "SubFormListFieldModel",
    "DisplaySubItemFieldModel",
    "DisplaySubListFieldModel"
  ].includes(String(fieldUse || "").trim());
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  FLOW_SURFACE_INTERNAL_FIELD_KEYS,
  FLOW_SURFACE_PUBLIC_FIELD_TYPE_SET,
  FLOW_SURFACE_PUBLIC_RELATION_FIELD_TYPES,
  FLOW_SURFACE_RESERVED_RELATION_FIELD_TYPES,
  assertNoInternalFieldKeys,
  getPublicFieldTypeForUse,
  normalizePublicFieldNameList,
  normalizePublicFieldType,
  resolveRelationFieldType,
  usesNestedRelationFields
});
