;
{
  try {
    let e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
    n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "be7708b8-b071-4bad-b74f-562f9bfa529c", e._sentryDebugIdIdentifier = "sentry-dbid-be7708b8-b071-4bad-b74f-562f9bfa529c");
  } catch (e) {
  }
}
;
import { T as TrustedFieldsProviders } from "./Image-C0SMWMbc.js";
import { f as formDebugInfo } from "./debugStore-BvbyN1Oi.js";
import { a3 as createLogger, b4 as businessDetailsApiKeyMapping, aG as individualOnfidoApiKeyMapping, b5 as remediationHasFileUploadField, b6 as dataMissingRemediationsToFieldsMap, aD as keysOf } from "./StoreProvider-CqQrndhS.js";
const linkedFieldsMap = {
  "additionalInformation.vatNumber": [
    "additionalInformation.exemptedFromVat",
    "additionalInformation.vatAbsenceReason"
  ]
};
function calculateLinkedRequiredFields({
  field,
  formId,
  customRules,
  scenarioConfiguration,
  dataMissingErrors,
  formFieldsWithExistingData
}) {
  const tldsField = makeTLDSFieldName(formId, field);
  const isRootField = Boolean(linkedFieldsMap[tldsField]);
  if (isRootField) {
    const linkedFields = linkedFieldsMap[tldsField];
    const fieldSettings = scenarioConfiguration?.[field];
    const isFieldRequiredBySettings = fieldSettings && isFieldRequired(fieldSettings, customRules);
    const isFieldPopulated = formFieldsWithExistingData?.includes(field);
    const isFieldNeededToRemediateDataMissingError = isFieldRequiredToRemediateDataMissingError(
      formId,
      field,
      dataMissingErrors
    );
    const areLinkedFieldsPopulated2 = linkedFields?.some((linkedField) => {
      const linkedFieldKey = linkedField.split(".")[1];
      const isLinkedFieldPopulated = formFieldsWithExistingData?.includes(linkedFieldKey);
      return isLinkedFieldPopulated;
    });
    const isRootFieldRequired2 = isFieldRequiredBySettings || isFieldPopulated || isFieldNeededToRemediateDataMissingError || areLinkedFieldsPopulated2;
    if (!isRootFieldRequired2) {
      return {
        isRequiredFromLinkedField: false,
        isOptionalFromLinkedField: false
      };
    }
    switch (field) {
      case "vatNumber": {
        const processedRule = customRules["countryUsesVat"]?.();
        return {
          isRequiredFromLinkedField: processedRule === "REQUIRED",
          isOptionalFromLinkedField: processedRule === "OPTIONAL"
        };
      }
    }
  }
  const rootLinkedField = Object.entries(linkedFieldsMap).find(
    ([, linkedFields]) => linkedFields.includes(tldsField)
  )?.[0];
  if (!rootLinkedField)
    return {
      isRequiredFromLinkedField: false,
      isOptionalFromLinkedField: false
    };
  const rootFieldKey = rootLinkedField.split(".")[1];
  const rootFieldSettings = scenarioConfiguration?.[rootFieldKey];
  const isRootFieldRequired = rootFieldSettings && isFieldRequired(rootFieldSettings, customRules);
  const isRootFieldPopulated = formFieldsWithExistingData?.includes(rootFieldKey);
  const areLinkedFieldsPopulated = linkedFieldsMap[rootLinkedField]?.some(
    (linkedField) => {
      const fieldKey = linkedField.split(".")[1];
      return formFieldsWithExistingData?.includes(fieldKey);
    }
  );
  const isRootFieldRequiredToRemediateDataMissingError = isFieldRequiredToRemediateDataMissingError(
    formId,
    rootFieldKey,
    dataMissingErrors
  );
  const isRootLinkedFieldRequired = isRootFieldRequired || isRootFieldPopulated || areLinkedFieldsPopulated || isRootFieldRequiredToRemediateDataMissingError;
  if (!isRootLinkedFieldRequired) {
    return {
      isRequiredFromLinkedField: false,
      isOptionalFromLinkedField: false
    };
  }
  switch (field) {
    case "exemptedFromVat": {
      const processedRule = customRules["isVatExempt"]?.();
      return {
        isRequiredFromLinkedField: processedRule === "REQUIRED",
        isOptionalFromLinkedField: processedRule === "OPTIONAL"
      };
    }
    case "vatAbsenceReason": {
      const processedRule = customRules["isVatExempt"]?.();
      return {
        isRequiredFromLinkedField: processedRule === "REQUIRED",
        isOptionalFromLinkedField: processedRule === "OPTIONAL"
      };
    }
    default:
      return {
        isRequiredFromLinkedField: false,
        isOptionalFromLinkedField: false
      };
  }
}
const logger = createLogger();
const composePerScenarioFormConfigurations = (scenarios = [], configurations) => scenarios.reduce(
  (composedConfiguration, scenarioName) => ({
    ...composedConfiguration,
    ...configurations[scenarioName]
  }),
  {}
);
const augmentWithCountryConfigs = (countrySpecificConfig, baseFormConfig) => {
  if (!countrySpecificConfig) return baseFormConfig;
  return keysOf(countrySpecificConfig).reduce(
    (mergedConfig, field) => ({
      ...mergedConfig,
      [field]: {
        ...baseFormConfig[field],
        ...countrySpecificConfig[field]
      }
    }),
    baseFormConfig
  );
};
const evaluateRules = (fieldSettings, customRules) => {
  const ruleNames = [fieldSettings.rule, ...fieldSettings.rules ?? []].filter(
    Boolean
  );
  const rules = ruleNames.map((ruleName) => {
    switch (ruleName) {
      case "REQUIRED":
        return () => "REQUIRED";
      case "OPTIONAL":
        return () => "OPTIONAL";
      default: {
        const ruleFn = customRules[ruleName];
        if (!ruleFn) {
          logger.error(`Rule with name '${ruleName}' is not defined`);
          return () => void 0;
        }
        return ruleFn;
      }
    }
  });
  return rules.map((rule, index) => ({
    ruleName: ruleNames[index],
    result: rule()
  }));
};
const isFieldRequired = (fieldSettings, customRules, reasons) => {
  const ruleResults = evaluateRules(fieldSettings, customRules);
  if (reasons) {
    ruleResults.forEach(({ ruleName, result }) => {
      reasons.push(`Rule '${ruleName}': ${result ?? "undefined"}`);
    });
  }
  return ruleResults.every(({ result }) => result === "REQUIRED");
};
const isFieldOptional = (fieldSettings, customRules, reasons) => {
  const ruleResults = evaluateRules(fieldSettings, customRules);
  return ruleResults.every(({ result }) => result === "OPTIONAL");
};
function getPropsFromConfigurations({
  scenarioConfiguration,
  forms,
  remediationActions,
  dataMissingErrors,
  fieldsWithExistingData,
  // TODO can type more strictly as `MappingKey<FormSchema>`
  customRules,
  legalEntityType,
  legalEntityTrustedFields,
  remediationFieldAsOptional = false
}) {
  const requiredFields = {};
  const optionalFields = {};
  const allFields = {};
  const obscuredFields = {};
  const trustedFields = {};
  const fieldDebugStore = {};
  formDebugInfo.value = {};
  if (!scenarioConfiguration) {
    return;
  }
  const readonly = ["legalFormDescription"];
  const trustedFieldMappings = legalEntityTrustedFields?.reduce((acc, trusted) => {
    switch (trusted.provider) {
      case TrustedFieldsProviders.KOMPANY: {
        if (legalEntityType === "organization") {
          return [
            ...acc,
            ...trusted.fields.map(
              (tf) => businessDetailsApiKeyMapping[tf]
            )
          ];
        }
        return acc;
      }
      case TrustedFieldsProviders.SINGPASS: {
        if (legalEntityType === "organization") {
          const orgFields = trusted.fields.filter(
            (field) => field.split(".")[0] === "organization"
          );
          return [
            ...acc,
            ...orgFields.map(
              (tf) => businessDetailsApiKeyMapping[tf]
            )
          ];
        }
        if (legalEntityType === "individual") {
          const individualFields = trusted.fields.filter(
            (field) => field.split(".")[0] === "individual"
          );
          return [
            ...acc,
            ...individualFields.map(
              (tf) => individualOnfidoApiKeyMapping[tf]
            )
          ];
        }
        return acc;
      }
      default:
        return acc;
    }
  }, []);
  Object.entries(forms).forEach(([_formId, formDetails]) => {
    const formId = _formId;
    const formFieldsWithExistingData = fieldsWithExistingData.filter((field) => field.startsWith(formId)).map((field) => field.slice(field.lastIndexOf(".") + 1));
    if (trustedFieldMappings) {
      trustedFields[formId] = getFormTrustedFields(formId, trustedFieldMappings);
    }
    formDetails.fields?.forEach((_field) => {
      const field = _field;
      const fieldName = `${formId}.${field}`;
      const reasons = [];
      const fieldSettings = scenarioConfiguration[field];
      const isRequiredFromFieldConfig = fieldSettings && isFieldRequired(fieldSettings, customRules, reasons);
      const isOptionalFromFieldConfig = fieldSettings && isFieldOptional(fieldSettings, customRules);
      const isFieldRequiredByRemediationAction = showRemediationField(field, remediationActions);
      if (isFieldRequiredByRemediationAction) reasons.push("Required by remediation action");
      const isFieldNeededToRemediateDataMissingError = isFieldRequiredToRemediateDataMissingError(
        formId,
        field,
        dataMissingErrors
      );
      if (isFieldNeededToRemediateDataMissingError)
        reasons.push("Required to remediate dataMissing error");
      const isRequiredByRemediationAction = !remediationFieldAsOptional && isFieldRequiredByRemediationAction;
      const isOptionalByRemediationAction = remediationFieldAsOptional && isFieldRequiredByRemediationAction;
      const isRequiredFieldPopulated = !isOptionalFromFieldConfig && formFieldsWithExistingData.includes(field);
      if (isRequiredFieldPopulated) reasons.push("Required because field is already populated");
      const { isRequiredFromLinkedField, isOptionalFromLinkedField } = calculateLinkedRequiredFields({
        field,
        formId,
        customRules,
        scenarioConfiguration,
        dataMissingErrors,
        formFieldsWithExistingData
      });
      if (isRequiredFromLinkedField) reasons.push("Required by linked field");
      if (isOptionalFromLinkedField) reasons.push("Optional by linked field");
      const isRequired = (isRequiredFromFieldConfig || isRequiredByRemediationAction || isFieldNeededToRemediateDataMissingError || isRequiredFieldPopulated || isRequiredFromLinkedField) && !isOptionalFromLinkedField;
      if (isRequired && !readonly.includes(field)) {
        requiredFields[formId] = requiredFields[formId] ? [...requiredFields[formId], field] : [field];
        allFields[formId] = allFields[formId] ? [...allFields[formId], field] : [field];
      }
      const isOptional = !isRequired && (isOptionalFromFieldConfig || isOptionalByRemediationAction || isOptionalFromLinkedField);
      if (isOptional) {
        optionalFields[formId] = optionalFields[formId] ? [...optionalFields[formId], field] : [field];
        allFields[formId] = allFields[formId] ? [...allFields[formId], field] : [field];
      }
      fieldDebugStore[fieldName] = {
        status: isRequired ? "REQUIRED" : isOptional ? "OPTIONAL" : "HIDDEN",
        reasons
      };
      if (fieldSettings?.obscured) {
        obscuredFields[formId] = obscuredFields[formId] ? [...obscuredFields[formId], field] : [field];
      }
    });
  });
  formDebugInfo.value = fieldDebugStore;
  return {
    requiredFields,
    optionalFields,
    allFields,
    obscuredFields,
    trustedFields
  };
}
const showRemediationField = (field, remediationActions) => remediationActions.some(
  (rem) => rem.fields?.includes(field) && remediationHasFileUploadField(rem)
);
const makeTLDSFieldName = (formId, fieldName) => {
  if (fieldName === "proofOfOrganizationTaxInfo") {
    return `${formId}.taxDocument`;
  }
  return `${formId}.${fieldName}`;
};
const isFieldRequiredToRemediateDataMissingError = (formId, field, dataMissingErrors) => {
  const dataMissingRemediations = dataMissingErrors.flatMap((error) => error.remediatingActions).filter(
    (remediatingAction) => !!remediatingAction && remediatingAction.code in dataMissingRemediationsToFieldsMap
  );
  const missingFields = dataMissingRemediations.flatMap((remediatingAction) => dataMissingRemediationsToFieldsMap[remediatingAction.code]).filter((missingField) => Boolean(missingField)).map((missingField) => makeTLDSFieldName(formId, missingField));
  return missingFields.includes(makeTLDSFieldName(formId, field));
};
const getFormTrustedFields = (formId, trustedFields) => trustedFields.filter((field) => field.split(".")[0] === formId).map(
  (field) => field.split(".").filter((item) => formId !== item).join(".")
);
export {
  augmentWithCountryConfigs as a,
  composePerScenarioFormConfigurations as c,
  getPropsFromConfigurations as g
};
