/**
 * Applies parameter values from a params object to a list of field definitions.
 *
 * For each field in the fields array, if a property with the same name exists in params,
 * the field's value will be set to the corresponding value from params.
 *
 * If a formInstance is provided, its fields property will be updated as well.
 *
 * @param {Array<Object>} fields - The array of field definition objects. Each object should have a 'name' property.
 * @param {Object} params - The object containing parameter values, typically from URL query params.
 * @returns {Array<Object>} A new array of field objects with updated 'value' properties where applicable.
 */
export const applyParamsToFields = (fields, params) => {
  if (!params || !fields) return fields
  const updatedFields = fields.map(field => {
    if (params.hasOwnProperty(field.name)) {
      switch (field.type) {
        case 'select':
          if (field.options && typeof params[field.name] === 'string') {
            const paramValue = params[field.name]
            const matchedOption = field.options.find(opt =>
              typeof opt.value === 'string'
                ? opt.value.toLowerCase() === paramValue.toLowerCase()
                : opt.value === paramValue
            )
            if (matchedOption) {
              return { ...field, value: matchedOption.value }
            }
          }
          break
        default:
          return { ...field, value: params[field.name] }
      }
      return field
    }
    return field
  })

  return updatedFields
}
