require 'lib/executors/stack_executor/stack_servers_fetcher'
require 'providers/aws'

class Devops::Executor::StackExecutor
  RSpec.describe StackServersFetcher do
    def info_hash_for_id(id)
      {
        'id' => id,
        'name' => 'server_name',
        'key_name' => 'key',
        'private_ip' => '127.0.0.1',
        'public_ip' => '127.0.0.2',
        'tags' => {
          'cid:priority' => '3',
          'Name' => 'server1'
        }
      }
    end

    let(:out) { double('out', puts: nil, flush: nil) }
    let(:stack) { build(:stack_aws) }
    let(:fetcher) { described_class.new(stack, out) }
    let(:new_server_info) { info_hash_for_id('i-new') }
    let(:persisted_server_info) { info_hash_for_id('i-persisted') }
    let(:stale_server) { build(:server, id: 'i-deleted') }

    before do
      allow(Devops::Model::Server).to receive(:stack_servers) { [stale_server, build(:server, id: 'i-persisted')] }
      provider = instance_double(Provider::AwsConnector, name: 'aws')
      allow(stack).to receive(:provider_instance) { provider }
      allow(provider).to receive(:stack_servers) {[new_server_info, persisted_server_info]}
    end

    describe '#new_servers_by_priorities' do
      let(:new_servers_by_priorities) { fetcher.new_servers_by_priorities }

      it 'returns new servers info by :new key divided by priorities' do
        expect(new_servers_by_priorities).to be_a(Hash)
        expect(new_servers_by_priorities.length).to eq 1
        expect(new_servers_by_priorities[3].length).to eq 1
        expect(new_servers_by_priorities[3].first).to eq new_server_info
      end

      it "sets priority to 0 if it's absent" do
        new_server_info['tags'].delete('cid:priority')
        expect(new_servers_by_priorities[0].first).to eq new_server_info
      end
    end

    describe '#stale_servers' do
      it 'returns array of stale servers' do
        expect(fetcher.stale_servers).to match_array [stale_server]
      end
    end
  end
end