# frozen_string_literal: true

require 'spec_helper'
require 'app'

describe 'LambdaFunction::Handler' do
  describe '#process' do
    let(:event) do
      {
        'chef_client_key_secret_id' => 'CHEF_CLIENT_KEY',
        'chef_encrypted_data_bag_secret_id' => 'CHEF_ENCRYPTED_DATA_BAG_SECRET',
        'chef_server_certificate_secret_id' => 'CHEF_SERVER_CERTIFICATE',
        'chef_server_url' => 'https://chef.theorchard.io'
      }
    end

    let(:context) do
      Class.new do
        def self.function_name
          'test-function'
        end
      end
    end

    before do
      allow(Datadog::Lambda).to receive(:wrap).and_yield
      allow(Utils::SSM).to receive(:create_activation).and_return(
        'activation_id' => 'foo',
        'activation_code' => 'bar'
      )
      allow(Utils::Chef).to receive(:configure)
      allow(Utils::Chef).to receive(:create_encrypted_data_bag)
      allow(Utils::Secrets).to receive(:get_secret).and_return('secret')
      stub_const('Config::CHEF_DATA_BAG_ITEM_NAME', 'test')
    end

    it 'creates an SSM activation and stores the details in a Chef data bag' do
      LambdaFunction::Handler.process(event: event, context: context)
      expect(Utils::Chef).to have_received(:create_encrypted_data_bag).once.with(
        data: {
          'id' => 'test',
          'activation_id' => 'foo',
          'activation_code' => 'bar'
        },
        secret: 'secret'
      )
    end
  end
end
