const getDeepValues = require('../../helpers/get-deep-values');

/**
 * @param {*} value
 * @returns {string[]}
 */
function extractContentKeys(value) {
  let output = [];

  if (!value || typeof value !== 'object') return output;

  if (typeof value.content_key === 'string') {
    return [value.content_key];
  }

  if (value.content_key && typeof value.content_key === 'object') {
    return (
      Object.values(value.content_key)
        /**
         * Need to support deeply nested `content_key` structures:
         *
         * ```json
         *   {
         *     "content_key": {
         *       "label": "form.last_name.label"
         *     }
         *   }
         * ```
         * as well as this:
         * ```json
         *   {
         *     "content_key": {
         *       "last_name": {
         *         "label": "form.last_name.label"
         *       }
         *     }
         *   }
         * ```
         */
        .reduce((acc, subValue) => acc.concat(getDeepValues(subValue, true)), [])
        .filter((subValue) => !!subValue)
    );
  }

  if (value.type === 'form-input-monetary' && value.config && value.config.field_name) {
    output = output.concat(
      `form.${value.config.field_name}_human.errors.required`,
      `form.${value.config.field_name}_human.errors.monetary`,
    );
  }

  if (value.type === 'form-input-uplaod' && value.config && value.config.field_name) {
    output = output.concat(
      `form.${value.config.field_name}.errors.virus_detected`,
      `form.${value.config.field_name}.errors.invalid_file_format`,
    );
  }

  Object.keys(value).forEach((key) => {
    output = [...output, ...extractContentKeys(value[key])];
  });

  return output;
}

module.exports = extractContentKeys;
