# Updates an attribute for a given model to ensure it is unique
class DuplicateRemover
  ERROR_MESSAGE_WHEN_INVALID = "has already been taken"

  def initialize(record, attribute)
    @record = record
    @attribute = attribute
    @original_attribute_value = record.send(attribute)
    @current_index = 2
  end

  def perform!
    while duplicate?
      record.send("#{attribute}=", new_name)
      increment_index
    end

    record.save!
  end

  private

  attr_reader :attribute, :current_index, :original_attribute_value, :record

  def duplicate?
    !record.valid? && record.errors[attribute].include?(ERROR_MESSAGE_WHEN_INVALID)
  end

  def increment_index
    @current_index += 1
  end

  def new_name
    [original_attribute_value, "(#{current_index})"].join(" ")
  end
end
