"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.searchableSnapshotFields = exports.getSchema = void 0;
var _i18n = require("@kbn/i18n");
var _shared_imports = require("../../../../shared_imports");
var _constants = require("../../../constants");
var _constants2 = require("../constants");
var _i18n_texts = require("../i18n_texts");
var _validations = require("./validations");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const rolloverFormPaths = Object.values(_constants2.ROLLOVER_FORM_PATHS);
const {
  emptyField,
  numberGreaterThanField
} = _shared_imports.fieldValidators;
const serializers = {
  stringToNumber: v => v != null ? parseInt(v, 10) : undefined
};
const maxNumSegmentsField = {
  label: _i18n_texts.i18nTexts.editPolicy.maxNumSegmentsFieldLabel,
  validations: [{
    validator: emptyField(_i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.forcemerge.numberOfSegmentsRequiredError', {
      defaultMessage: 'A value for number of segments is required.'
    }))
  }, {
    validator: _validations.ifExistsNumberGreaterThanZero
  }],
  serializer: serializers.stringToNumber
};
const searchableSnapshotFields = {
  snapshot_repository: {
    label: _i18n_texts.i18nTexts.editPolicy.searchableSnapshotsRepoFieldLabel,
    validations: [{
      validator: emptyField(_i18n_texts.i18nTexts.editPolicy.errors.searchableSnapshotRepoRequired)
    }],
    // TODO: update text copy
    helpText: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.searchableSnapshot.repositoryHelpText', {
      defaultMessage: 'Each phase uses the same snapshot repository.'
    })
  },
  storage: {
    label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.searchableSnapshot.storageLabel', {
      defaultMessage: 'Storage'
    }),
    helpText: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.searchableSnapshot.storageHelpText', {
      defaultMessage: "Type of snapshot mounted for the searchable snapshot. This is an advanced option. Only change it if you know what you're doing."
    })
  }
};
exports.searchableSnapshotFields = searchableSnapshotFields;
const numberOfReplicasField = {
  label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.numberOfReplicasLabel', {
    defaultMessage: 'Number of replicas'
  }),
  validations: [{
    validator: emptyField(_i18n_texts.i18nTexts.editPolicy.errors.numberRequired)
  }, {
    validator: _validations.ifExistsNumberNonNegative
  }],
  serializer: serializers.stringToNumber
};
const numberOfShardsField = {
  label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.shrink.numberOfPrimaryShardsLabel', {
    defaultMessage: 'Number of primary shards'
  }),
  defaultValue: 1,
  validations: [{
    validator: emptyField(_i18n_texts.i18nTexts.editPolicy.errors.numberRequired)
  }, {
    validator: numberGreaterThanField({
      message: _i18n_texts.i18nTexts.editPolicy.errors.numberGreatThan0Required,
      than: 0
    })
  }],
  serializer: serializers.stringToNumber
};
const shardSizeField = {
  label: _i18n_texts.i18nTexts.editPolicy.maxPrimaryShardSizeLabel,
  validations: [{
    validator: emptyField(_i18n_texts.i18nTexts.editPolicy.errors.numberRequired)
  }, {
    validator: numberGreaterThanField({
      message: _i18n_texts.i18nTexts.editPolicy.errors.numberGreatThan0Required,
      than: 0
    })
  }],
  serializer: serializers.stringToNumber
};
const getPriorityField = phase => ({
  defaultValue: _constants.defaultIndexPriority[phase],
  label: _i18n_texts.i18nTexts.editPolicy.indexPriorityFieldLabel,
  validations: [{
    validator: emptyField(_i18n_texts.i18nTexts.editPolicy.errors.numberRequired)
  }, {
    validator: _validations.ifExistsNumberNonNegative
  }],
  serializer: serializers.stringToNumber
});
const getMinAgeField = (phase, defaultValue) => ({
  defaultValue,
  // By passing an empty array we make sure to *not* trigger the validation when the field value changes.
  // The validation will be triggered when the millisecond variant (in the _meta) is updated (in sync)
  fieldsToValidateOnChange: [],
  validations: [{
    validator: emptyField(_i18n_texts.i18nTexts.editPolicy.errors.numberRequired)
  }, {
    validator: _validations.ifExistsNumberNonNegative
  }, {
    validator: _validations.integerValidator
  }, {
    validator: (0, _validations.minAgeGreaterThanPreviousPhase)(phase)
  }]
});
const getDownsampleFieldsToValidateOnChange = (p, includeCurrentPhase = true) => {
  const allPhases = ['hot', 'warm', 'cold'];
  const getIntervalSizePath = currentPhase => `_meta.${currentPhase}.downsample.fixedIntervalSize`;
  const omitPreviousPhases = currentPhase => allPhases.slice(allPhases.indexOf(currentPhase) + (includeCurrentPhase ? 0 : 1));
  // when a phase is validated, need to also validate all downsample intervals in the next phases
  return omitPreviousPhases(p).map(getIntervalSizePath);
};
const getDownsampleSchema = phase => {
  return {
    enabled: {
      defaultValue: false,
      label: _i18n_texts.i18nTexts.editPolicy.downsampleEnabledFieldLabel,
      fieldsToValidateOnChange: getDownsampleFieldsToValidateOnChange(phase, /* don't trigger validation on the current validation to prevent showing error state on pristine input */
      false)
    },
    fixedIntervalSize: {
      label: _i18n_texts.i18nTexts.editPolicy.downsampleIntervalFieldLabel,
      fieldsToValidateOnChange: getDownsampleFieldsToValidateOnChange(phase),
      validations: [{
        validator: emptyField(_i18n_texts.i18nTexts.editPolicy.errors.numberRequired)
      }, {
        validator: _validations.ifExistsNumberGreaterThanZero
      }, {
        validator: _validations.integerValidator
      }, {
        validator: (0, _validations.downsampleIntervalMultipleOfPreviousOne)(phase)
      }]
    },
    fixedIntervalUnits: {
      defaultValue: 'd',
      fieldsToValidateOnChange: getDownsampleFieldsToValidateOnChange(phase)
    }
  };
};
const getSchema = isCloudEnabled => ({
  _meta: {
    hot: {
      isUsingDefaultRollover: {
        defaultValue: true,
        label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.hotPhase.isUsingDefaultRollover', {
          defaultMessage: 'Use recommended defaults'
        })
      },
      customRollover: {
        enabled: {
          defaultValue: true,
          label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.hotPhase.enableRolloverLabel', {
            defaultMessage: 'Enable rollover'
          })
        },
        maxStorageSizeUnit: {
          defaultValue: 'gb'
        },
        maxPrimaryShardSizeUnit: {
          defaultValue: 'gb'
        },
        maxAgeUnit: {
          defaultValue: 'd'
        }
      },
      bestCompression: {
        label: _i18n_texts.i18nTexts.editPolicy.bestCompressionFieldLabel
      },
      readonlyEnabled: {
        defaultValue: false,
        label: _i18n_texts.i18nTexts.editPolicy.readonlyEnabledFieldLabel
      },
      shrink: {
        isUsingShardSize: {
          defaultValue: false
        },
        maxPrimaryShardSizeUnits: {
          defaultValue: 'gb'
        }
      },
      downsample: getDownsampleSchema('hot')
    },
    warm: {
      enabled: {
        defaultValue: false,
        label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.warmPhase.activateWarmPhaseSwitchLabel', {
          defaultMessage: 'Activate warm phase'
        })
      },
      minAgeUnit: {
        defaultValue: 'd'
      },
      minAgeToMilliSeconds: {
        defaultValue: -1,
        fieldsToValidateOnChange: ['phases.warm.min_age', 'phases.cold.min_age', 'phases.frozen.min_age', 'phases.delete.min_age']
      },
      bestCompression: {
        label: _i18n_texts.i18nTexts.editPolicy.bestCompressionFieldLabel
      },
      dataTierAllocationType: {
        label: _i18n_texts.i18nTexts.editPolicy.allocationTypeOptionsFieldLabel
      },
      allocationNodeAttribute: {
        label: _i18n_texts.i18nTexts.editPolicy.allocationNodeAttributeFieldLabel
      },
      readonlyEnabled: {
        defaultValue: false,
        label: _i18n_texts.i18nTexts.editPolicy.readonlyEnabledFieldLabel
      },
      shrink: {
        isUsingShardSize: {
          defaultValue: false
        },
        maxPrimaryShardSizeUnits: {
          defaultValue: 'gb'
        }
      },
      downsample: getDownsampleSchema('warm')
    },
    cold: {
      enabled: {
        defaultValue: false,
        label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.coldPhase.activateColdPhaseSwitchLabel', {
          defaultMessage: 'Activate cold phase'
        })
      },
      readonlyEnabled: {
        defaultValue: false,
        label: _i18n_texts.i18nTexts.editPolicy.readonlyEnabledFieldLabel
      },
      minAgeUnit: {
        defaultValue: 'd'
      },
      minAgeToMilliSeconds: {
        defaultValue: -1,
        fieldsToValidateOnChange: ['phases.cold.min_age', 'phases.frozen.min_age', 'phases.delete.min_age']
      },
      dataTierAllocationType: {
        label: _i18n_texts.i18nTexts.editPolicy.allocationTypeOptionsFieldLabel
      },
      allocationNodeAttribute: {
        label: _i18n_texts.i18nTexts.editPolicy.allocationNodeAttributeFieldLabel
      },
      downsample: getDownsampleSchema('cold')
    },
    frozen: {
      enabled: {
        defaultValue: false,
        label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.frozenPhase.activateFrozenPhaseSwitchLabel', {
          defaultMessage: 'Activate frozen phase'
        })
      },
      minAgeUnit: {
        defaultValue: 'd'
      },
      minAgeToMilliSeconds: {
        defaultValue: -1,
        fieldsToValidateOnChange: ['phases.frozen.min_age', 'phases.delete.min_age']
      },
      dataTierAllocationType: {
        label: _i18n_texts.i18nTexts.editPolicy.allocationTypeOptionsFieldLabel
      },
      allocationNodeAttribute: {
        label: _i18n_texts.i18nTexts.editPolicy.allocationNodeAttributeFieldLabel
      }
    },
    delete: {
      enabled: {
        defaultValue: false,
        label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.deletePhase.activateWarmPhaseSwitchLabel', {
          defaultMessage: 'Activate delete phase'
        })
      },
      minAgeUnit: {
        defaultValue: 'd'
      },
      minAgeToMilliSeconds: {
        defaultValue: -1,
        fieldsToValidateOnChange: ['phases.delete.min_age']
      }
    },
    searchableSnapshot: {
      repository: {
        defaultValue: isCloudEnabled ? _constants2.CLOUD_DEFAULT_REPO : ''
      }
    }
  },
  phases: {
    hot: {
      actions: {
        rollover: {
          max_age: {
            label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.hotPhase.maximumAgeLabel', {
              defaultMessage: 'Maximum age'
            }),
            validations: [{
              validator: _validations.rolloverThresholdsValidator
            }, {
              validator: _validations.ifExistsNumberGreaterThanZero
            }, {
              validator: _validations.integerValidator
            }],
            fieldsToValidateOnChange: rolloverFormPaths
          },
          max_docs: {
            label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.hotPhase.maximumDocumentsLabel', {
              defaultMessage: 'Maximum documents'
            }),
            validations: [{
              validator: _validations.rolloverThresholdsValidator
            }, {
              validator: _validations.ifExistsNumberGreaterThanZero
            }, {
              validator: _validations.integerValidator
            }],
            serializer: serializers.stringToNumber,
            fieldsToValidateOnChange: rolloverFormPaths
          },
          max_primary_shard_size: {
            label: _i18n_texts.i18nTexts.editPolicy.maxPrimaryShardSizeLabel,
            validations: [{
              validator: _validations.rolloverThresholdsValidator
            }, {
              validator: _validations.ifExistsNumberGreaterThanZero
            }],
            fieldsToValidateOnChange: rolloverFormPaths
          },
          max_primary_shard_docs: {
            label: _i18n_texts.i18nTexts.editPolicy.maxPrimaryShardDocsLabel,
            validations: [{
              validator: _validations.rolloverThresholdsValidator
            }, {
              validator: _validations.ifExistsNumberGreaterThanZero
            }, {
              validator: _validations.integerValidator
            }],
            serializer: serializers.stringToNumber,
            fieldsToValidateOnChange: rolloverFormPaths
          },
          max_size: {
            label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.hotPhase.maximumIndexSizeLabel', {
              defaultMessage: 'Maximum index size'
            }),
            validations: [{
              validator: _validations.rolloverThresholdsValidator
            }, {
              validator: _validations.ifExistsNumberGreaterThanZero
            }],
            fieldsToValidateOnChange: rolloverFormPaths
          }
        },
        forcemerge: {
          max_num_segments: maxNumSegmentsField
        },
        shrink: {
          number_of_shards: numberOfShardsField,
          max_primary_shard_size: shardSizeField
        },
        set_priority: {
          priority: getPriorityField('hot')
        },
        searchable_snapshot: searchableSnapshotFields
      }
    },
    warm: {
      min_age: getMinAgeField('warm'),
      actions: {
        allocate: {
          number_of_replicas: numberOfReplicasField
        },
        shrink: {
          number_of_shards: numberOfShardsField,
          max_primary_shard_size: shardSizeField
        },
        forcemerge: {
          max_num_segments: maxNumSegmentsField
        },
        set_priority: {
          priority: getPriorityField('warm')
        }
      }
    },
    cold: {
      min_age: getMinAgeField('cold'),
      actions: {
        allocate: {
          number_of_replicas: numberOfReplicasField
        },
        set_priority: {
          priority: getPriorityField('cold')
        },
        searchable_snapshot: searchableSnapshotFields
      }
    },
    frozen: {
      min_age: getMinAgeField('frozen'),
      actions: {
        allocate: {
          number_of_replicas: numberOfReplicasField
        },
        set_priority: {
          priority: getPriorityField('frozen')
        },
        searchable_snapshot: searchableSnapshotFields
      }
    },
    delete: {
      min_age: getMinAgeField('delete', '365'),
      actions: {
        wait_for_snapshot: {
          policy: {
            label: _i18n.i18n.translate('xpack.indexLifecycleMgmt.editPolicy.waitForSnapshot.snapshotPolicyFieldLabel', {
              defaultMessage: 'Policy name (optional)'
            })
          }
        }
      }
    }
  }
});
exports.getSchema = getSchema;