require 'rails_helper'

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

  let(:permission) { 'product_key_generation' }

  let(:test_handler_group_id) { 'test-handler-group-id' }
  let(:test_description) { 'test-description' }

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

      before do
        get :index
      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::HandlerGroup).to receive(:all).and_return(double(success?: true, status: 200, body: {'handler_groups' => []}))
        expect(Keys::HandlerGroup).to receive(:get).and_return(double(success?: true, status: 200, body: {'key_handler_group' => {
            'authorized_tuids' => [],
            'authorized_client_ids' => []
        }}))
        get :index, params: { handler_group_id: test_handler_group_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(:handler_group) { Keys::HandlerGroup.new }

      before do
        expect(Keys::HandlerGroup).to receive(:new).and_return(handler_group)
        expect(handler_group).to receive(:create).and_return(double(success?: true, status: 200))
        post :create, params: { keys_handler_group: { handler_group_id: test_handler_group_id, description: test_description, authorized_tuids_str: '', authorized_client_ids_str: ''} }
      end

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