require 'db/mongo/models/server'

RSpec.describe Devops::Model::Server, type: :model do
  let(:server) { build(:server) }

  it 'is valid with correct attrs' do
    expect(server).to be_valid
  end

  describe 'validation rules:', stubbed_logger: true do
    include_examples 'field type validation', :id, :raise_error_on_nil
    include_examples 'field type validation', :provider, :not_nil, :non_empty_string
    include_examples 'field type validation', :remote_user, :not_nil, :non_empty_string
    include_examples 'field type validation', :project, :not_nil, :non_empty_string
    include_examples 'field type validation', :environment, :not_nil, :non_empty_string
    include_examples 'field type validation', :private_ip, :not_nil, :non_empty_string
    include_examples 'field type validation', :public_ip, :maybe_nil, :maybe_empty_string
    include_examples 'field type validation', :ssh_key, :not_nil, :non_empty_string
    include_examples 'field type validation', :created_by, :not_nil, :non_empty_string
    include_examples 'field type validation', :cm_name, :not_nil, :non_empty_string
    include_examples 'field type validation', :reserved_by, :maybe_nil, :maybe_empty_string
    include_examples 'field type validation', :stack, :maybe_nil
    include_examples 'field type validation', :run_list, :maybe_empty_array, :run_list
  end

  it '#to_hash returns not nil fields' do
    server = described_class.new('id' => 'a', 'run_list' => [], 'project' =>  'asd')
    expect(server.to_hash.keys).to match_array(%w(id run_list project))
    server.stack = 'stack_id'
    expect(server.to_hash.keys).to match_array(%w(id run_list project stack))
  end

  describe '#info' do
    it 'returns string' do
      expect(server.info).to be_a(String)
    end
  end

  describe '#static?' do
    it 'returns true for servers with provider==static' do
      expect(build(:server, provider: 'static').static?).to be true
    end

    it 'returns false for servers with provider==ec2' do
      expect(server.static?).to be false
    end
  end

  describe '#set_last_operation', clean_db_after_example: true do
    it 'sets #last_operation.date to Time.now' do
      prev_operation_time = server.last_operation['date']
      server.set_last_operation('deploy', 'root', 'job_task')
      expect(server.last_operation['date']).to be > prev_operation_time
    end

    it 'updates last_operation_type' do
      server.set_last_operation('deploy', 'root', 'job_task')
      expect(server.last_operation['type']).to eq 'deploy'
    end

    it 'it raises error if given type is not supported' do
      expect {
        server.set_last_operation(:wrong, 'root')
      }.to raise_error ArgumentError
    end

    it 'expects string as an argument' do
      expect {
        server.set_last_operation(:deploy, 'root')
      }.to raise_error ArgumentError
    end
  end
end
