require 'rails_helper'

RSpec.describe Keys::ConfigurationsController do
  include_context 'mocked permissions'

  let(:permission) { 'product_key_generation' }

  let(:test_pool_id) { 'test-pool-id' }
  let(:test_metadata_key) { 'test-metadata-key' }
  let(:test_metadata_value) { 'test-metadata-value' }

  describe 'index' do
    context 'a user without permission' do
      include_context 'an unauthorized user'

      before do
        get :index, params: { pool_id: test_pool_id }
      end

      it_behaves_like 'it redirects the user and displays an error'
    end

    context 'a user with permission' do
      include_context 'an authorized user'

      before do
        expect(Keys::Configuration).to receive(:all).and_return(double(success?: true, status: 200, body: {'key_pool_metadata' => []}))
        get :index, params: { pool_id: test_pool_id }
      end

      it_behaves_like 'it returns a success response'
    end
  end

  describe 'create' do
    context 'a user without permission' do
      include_context 'an unauthorized user'

      before do
        post :create
      end

      it_behaves_like 'it redirects the user and displays an error'
    end

    context 'a user with permission' do
      include_context 'an authorized user'
      let(:configuration) { Keys::Configuration.new }

      before do
        expect(Keys::Configuration).to receive(:new).and_return(configuration)
        expect(configuration).to receive(:create).and_return(double(success?: true, status: 200))
        post :create, params: { keys_configuration: { pool_id: test_pool_id, metadata_key: test_metadata_key, metadata_value: test_metadata_value } }
      end

      it_behaves_like 'it redirects the user and displays a success message'
    end
  end

  describe 'delete' do
    context 'a user without permission' do
      include_context 'an unauthorized user'

      before do
        post :delete, params: { configuration_id: test_pool_id, pool_id: test_pool_id, metadata_key: test_metadata_key }
      end

      it_behaves_like 'it redirects the user and displays an error'
    end

    context 'a user with permission' do
      include_context 'an authorized user'

      let(:configuration) { Keys::Configuration.new }

      before do
        expect(Keys::Configuration).to receive(:from_attributes).and_return(configuration)
        expect(configuration).to receive(:delete).and_return(double(success?: true, status: 200))
        post :delete, params: { configuration_id: test_pool_id, pool_id: test_pool_id, metadata_key: test_metadata_key }
      end

      it_behaves_like 'it redirects the user and displays a success message'
    end
  end
end
