require 'rails_helper'

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

  let(:permission) { 'product_key_generation' }

  let(:test_pool_id) { 'test-pool' }
  let(:test_report_id) { 'test-report' }
  let(:test_download_url) { 'test-download-url' }
  let(:test_decryption_key_encoded) { 'dGVzdGtleQ==' }
  let(:test_decrypted_file) { 'test-decrypted-file' }

  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::Report).to receive(:all).and_return(double(success?: true, status: 200, body: {'key_pool_reports' => []}))
        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(:report) { Keys::Report.new }

      before do
        expect(Keys::Report).to receive(:new).and_return(report)
        expect(report).to receive(:generate_report).and_return(double(success?: true, status: 200))
        post :create, params: { keys_report: { pool_id: test_pool_id } }
      end

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

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

      before do
        post :download, params: { report_id: test_report_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'
      let(:report) { Keys::Report.new }
      before do
        expect(Keys::Report).to receive(:from_attributes).and_return(report)
        expect(report).to receive(:report_download_info).and_return(double(success?: true, status: 200, body: {'download_url' => test_download_url, 'decyption_key' => test_decryption_key_encoded}))
        expect(Keys::Report).to receive(:download_and_decrypt_report).and_return(test_decrypted_file)
        post :download, params: { report_id: test_report_id }
      end

      it_behaves_like 'it returns a success response'
    end
  end
end
