/**
 * @param {string} name
 * @param {FieldDefinitions} rules
 * @returns {string[]}
 */
function buildValidationKeys(name, rules) {
  if (typeof rules !== 'string') return [];

  return rules.split('|').reduce((acc, ruleChunk) => {
    const rule = ruleChunk.replace(/:.*/, '');

    if (rule === '' || /^(string|integer|boolean)$/.test(rule)) return acc;

    return [...acc, `form.${name}.errors.${rule}`];
  }, []);
}

/**
 * @param {*} value
 * @returns {string[]}
 */
function ensureArray(value) {
  if (!Array.isArray(value)) return [];

  return value;
}

/**
 * @param {Object.<string, {}>[]} definitionGroups
 * @returns {string[]}
 */
function extractFieldDefinitions(definitionGroups) {
  if (!definitionGroups || typeof definitionGroups !== 'object') return [];

  const allDefinitions = Object.values(definitionGroups).reduce(
    (acc, group) => [
      ...acc,
      ...ensureArray(group).reduce(
        (groupAcc, { name, validation }) => [...groupAcc, ...buildValidationKeys(name, validation)],
        [],
      ),
    ],
    [],
  );

  return allDefinitions;
}

module.exports = extractFieldDefinitions;

/**
 * @typedef {Object.<string, {}>} FieldDefinitions
 */
