require 'db/mongo/models/environment/environment'
require 'exceptions/non_existing_user'

RSpec.describe Devops::Model::Environment, type: :model do
  let(:env) { build(:environment) }

  before do
    create(:user, id: 'root')
  end

  after do
    Devops::Model::User.delete_all
  end

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

  describe 'validation rules:' do
    include_examples 'field type validation', :id, :not_nil, :non_empty_string, :only_word_symbols
    include_examples 'field type validation', :run_list, :maybe_empty_array, :run_list
    include_examples 'field type validation', :users, :maybe_empty_array
    include_examples 'field type validation', :expires, :maybe_nil, :non_empty_string

    it 'should be valid only with all users available' do
      expect(build(:environment, users: ['root'])).to be_valid
      expect(build(:environment, users: ['wrong'])).not_to be_valid
      expect(build(:environment, users: ['wrong', 'root'])).not_to be_valid
    end

    it 'expires should be smth like "2d" or "15h"' do
      expect(build(:environment, expires: '2d')).to be_valid
      expect(build(:environment, expires: 'wrong')).not_to be_valid
    end
  end

  describe '#initialize' do
    it 'sets id from given hash' do
      model = build(:environment, 'id' => 'a')
      expect(model.id).to eq 'a'
    end
    it 'sets uniq elements from run list from given hash' do
      model = build(:environment, 'run_list' => ['role[a]', 'role[a]', 'recipe[e]'])
      expect(model.run_list).to match_array ['role[a]', 'recipe[e]']
    end
    it 'sets empty array if run list is empty' do
      model = build(:environment, run_list: nil)
      expect(model.run_list).to match_array []
    end
    it 'sets expires from given hash' do
      model = build(:environment, 'expires' => '3d')
      expect(model.expires).to eq '3d'
    end
    it 'sets uniq users from given hash' do
      model = build(:environment, 'users' => ['root', 'root', 'user'])
      expect(model.users).to match_array ['root', 'user']
    end
  end

  describe '#to_hash' do
    it 'includes id, run_list, expires, users in keys' do
      expect(build(:environment).to_hash).to include('id', 'run_list', 'expires', 'users')
    end
  end

  describe '#add_users' do
    it "doesn't add duplications of already added users" do
      env = build(:environment, 'users' => %w(root user))
      env.add_users %w(root user)
      expect(env.users).to match_array %w(root user)
    end

    it "adds new users" do
      env = build(:environment, 'users' => %w(root))
      env.add_users ['user1', 'user2']
      expect(env.users).to match_array %w(root user1 user2)
    end
  end

  describe '#update_field', clean_db_after_example: true do
    subject { env.update_field('project_name', 'run_list', ['role[asd]']) }

    pending 'validate it' do
      expect(env).to receive(:validate_run_list!)
      subject
    end

    pending 'updates attribute value' do
      expect { subject }.to change {env.run_list}.to(['role[asd]'])
    end

    pending 'saves it' do
      expected_args = ['project_name', env.id, {'run_list' => ['role[asd]']}]
      expect { subject }.to change { described_class.count }
    end
  end

  # should be moved to categories specs
  describe '#create_role', stubbed_logger: true do
    subject { env.create_role('project_name') }
    before do
      allow(env).to receive_message_chain('knife_instance.role_name') { 'role_name' }
    end

    pending 'returns nil if knife_instance is nil' do
      allow(env).to receive(:knife_instance)
      expect(subject).to be nil
    end

    pending 'returns hash with :error if knife.roles is nil' do
      allow(env).to receive_message_chain('knife_instance.roles')
      expect(subject).to be_a(Hash).and include(:error)
    end

    pending 'returns hash with :error when creating a role raises an error' do
      allow(env).to receive_message_chain('knife_instance.roles') { [] }
      allow(env).to receive_message_chain('knife_instance.create_role') { raise StandardError }
      expect(subject).to be_a(Hash).and include(error: ['role_name'])
    end

    context 'when a role already exists in chef' do
      before { allow(env).to receive_message_chain('knife_instance.roles') { ['role_name'] } }
      pending 'returns hash with :exist' do
        expect(subject).to be_a(Hash).and include(exist: ['role_name'])
      end

      pending "adds the role to env's run_list" do
        subject
        expect(env.run_list).to include('role[role_name]')
      end
    end

    context 'when a role is missing in chef' do
      before { allow(env).to receive_message_chain('knife_instance.roles') { [] } }
      pending 'returns hash with :new when a role has been created' do
        expect(env).to receive_message_chain('knife_instance.create_role')
        expect(subject).to be_a(Hash).and include(new: ['role_name'])
      end

      pending "adds the role to env's run_list" do
        allow(env).to receive_message_chain('knife_instance.create_role')
        subject
        expect(env.run_list).to include('role[role_name]')
      end
    end
  end

  describe '#rename', stubbed_logger: true do
    subject { env.rename('project_id', 'new_name') }
    let(:old_role_name) {'project_id_name'}
    let(:new_role_name) {'project_id_new_name'}
    let(:suggested_old_roles) {["role[#{old_role_name}]"]}
    let(:suggested_new_roles) {["role[#{new_role_name}]"]}

    before do
      # simulate correct start conditions
      env.run_list = suggested_old_roles

      # stub calls to knife
      allow(env).to receive(:create_role) { {exist: [new_role_name]} }
      allow(env).to receive_message_chain('knife_instance.role_name') { old_role_name }

      # there is a call to Project.create_roles_response, stub it
      allow_message_expectations_on_nil
      project_class_double = double()
      allow(project_class_double).to receive(:create_roles_response) { ''}
      stub_const('Devops::Model::Project', project_class_double)
    end

    pending 'raises InvalidRecord if env with such name already exists in project' do
      project = build(:project, with_env_identifiers: %w(new_name))
      expect{subject}.to raise_error(InvalidRecord)
    end

    context 'when there is no env with such name already' do
      pending 'validates new id' do
        expect(env).to receive(:validate_identifier!)
        subject
      end

      pending 'removes old role and adds new one' do
        # somewhy 'expect to change' did't work
        expect(env.run_list).to match_array(suggested_old_roles)
        subject
        expect(env.run_list).to match_array(suggested_new_roles)
      end
    end
  end
end