module Validators
  class DeployEnv::DeployEnvs < Base

    def valid?
      envs = @model.deploy_envs.map {|d| d.identifier}
      non_uniq = envs.uniq.select{|u| envs.count(u) > 1}
      unless non_uniq.empty?
        @msg = "Deploy environment(s) '#{non_uniq.join("', '")}' is/are not unique"
        return false
      end
      @model.deploy_envs.each do |d|
        d.validate!
      end
      true
    end

    # do not rescue children validators' errors. With this:
    #   class of child validator's error doesn't disappeared
    #   logs doesn't contain two similar records
    def validate!
      raise error_class.new(message) unless valid?
    rescue InvalidRecord => e
      raise e
    rescue StandardError => e
      DevopsLogger.logger.error [e.message, e.backtrace].join("\n")
      raise error_class.new("An error raised during validation with #{self.class}: #{e.class}: #{e.message}")
    end

    def message
      "Invalid project: #{@msg}."
    end
  end
end
