# frozen_string_literal: true

require 'spec_helper'
require 'utils/chef'

describe 'Utils::Chef' do
  describe '#configure' do
    before do
      stub_const('Config::CHEF_CLIENT_NAME', 'test')
      stub_const('Config::TRUSTED_CERTS_DIR', '/tmp/configure_cert_test')
      FileUtils.remove_dir(Config::TRUSTED_CERTS_DIR, true)
      allow(Utils::Chef::S3_CLIENT).to receive(:get_object)
    end

    it 'configures the trusted certificates' do
      Utils::Chef.configure(
        chef_server_url: 'https://chef.theorchard.io',
        chef_client_key: 'foo',
        cert_s3_bucket: 'my-bucket',
        cert_s3_key: 'my-ssl-cert.crt'
      )
      expect(Utils::Chef::S3_CLIENT).to have_received(:get_object).once.with(
        response_target: '/tmp/configure_cert_test/chef.crt',
        bucket: 'my-bucket',
        key: 'my-ssl-cert.crt'
      )
    end

    it 'sets the Chef config' do
      Utils::Chef.configure(
        chef_server_url: 'https://chef.theorchard.io',
        chef_client_key: 'foo',
        cert_s3_bucket: 'my-bucket',
        cert_s3_key: 'my-ssl-cert.crt'
      )
      expect(Chef::Config).to have_attributes(
        node_name: 'test',
        chef_server_url: 'https://chef.theorchard.io',
        client_key_contents: 'foo',
        trusted_certs_dir: '/tmp/configure_cert_test'
      )
    end
  end

  describe '#create_encrypted_data_bag' do
    let(:data_bag_item) { Chef::DataBagItem.new }

    before do
      allow(Chef::EncryptedDataBagItem).to receive(:encrypt_data_bag_item).and_return({ 'id' => 'test',
                                                                                        'data' => 'encrypted' })
      allow(Chef::DataBagItem).to receive(:new).and_return(data_bag_item)
      allow(data_bag_item).to receive(:save)

      stub_const('Config::CHEF_DATA_BAG_NAME', 'foo')
    end

    it 'creates a data bag containing the given data encrypted with the given secret' do
      Utils::Chef.create_encrypted_data_bag(
        data: { 'id' => 'test', 'data' => 'unencrypted' },
        secret: 'abc'
      )
      expect(data_bag_item).to have_attributes(
        data_bag: 'foo',
        raw_data: { 'id' => 'test', 'data' => 'encrypted' }
      )
    end
  end
end
