require 'rails_helper'

module Tools
  RSpec.describe IpResolverController do
    include_context 'mocked permissions'
    let(:login_audit) { History::QueryAudit.from_attributes({ "uuid" => "836cf2b8-fd3e-54cd-9758-6a32927d441f", "action" => History::AUDIT_LOGIN_EVENT, "user_type" => "twitch_user", "user_id" => "109657733", "resource_type" => "twitch_user", "resource_id" => "109657733", "description" => "IP address: 192.168.42.82", "created_at" => "2017-05-31T00:42:19.027000000Z", "expired_at" => "2022-05-30T00:42:19.027000000Z", "expiry" => 157_680_000, "changes" => nil }) }
    let(:session_audit) { History::QueryAudit.from_attributes({ "uuid" => "87c43830-3423-5394-992c-25f59c70cbde", "action" => History::AUDIT_SESSION_START_EVENT, "user_type" => "twitch_user", "user_id" => "109657733", "resource_type" => "twitch_user", "resource_id" => "109657733", "description" => "IP address: 10.255.247.163", "created_at" => "2017-05-26T19:29:38.211000000Z", "expired_at" => "2022-05-25T19:29:38.211000000Z", "expiry" => 157_680_000, "changes" => nil }) }
    let(:audits_from_service) { PaginatedArray.new([login_audit, session_audit]) }
    let(:resolved_geo) { IpGeo.new('China', 'CN', 'Henan', 'Zijinglu', 34.76, 112.9714, 50, 'China Mobile Guangdong') }

    describe '#resolve' do
      context 'with no ip addresses' do
        let(:permission) { 'audits' }
        include_context 'an authorized user'

        before do
          get :resolve, :params => { 'resolve' => 'true' }
        end

        it 'should not throw an error' do
          expect(response.code).to eq('200')
          expect(flash[:error]).to be_nil
        end
      end

      describe 'permissions' do
        let(:permission) { 'audits' }
        let(:options) { {'resource_type' => 'twitch_user', 'page' => nil} }

        context 'with audits' do

          context 'a user with appropriate permissions' do
            include_context 'an authorized user'

            before do
              expect(History::QueryAudit).to receive(:all).with(ActionController::Parameters.new(options)).and_return(audits_from_service)
              expect(IpComparison).to receive(:geo_lookup_ip).twice.and_return(nil)
              post :resolve, :params => { :id => 'foo', 'resolve' => 'true', 'search' => options }
            end

            it_behaves_like 'it returns a success response'
          end

          context 'a user without appropriate permissions' do
            include_context 'an unauthorized user'

            before do
              post :resolve, :params => { :id => 'foo', 'resolve' => 'true', 'search' => options }
            end

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