require 'rails_helper'
require 'history_client'

module History
  describe QueryAudit do
    let(:user_id) {'109657733'}

    describe '#ips_for_twitch_user' do
      context "with history returning audits containing IP addresses in the expected field" do
        let(:audits_from_service) do
          {
            'audits' => [
              { "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 },
              { "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 }
            ],
            'total_pages' => 1,
          }
        end

        before do
          audits_from_client = History::QueryResult.from_hash(audits_from_service)
          expect(QueryAudit.client).to receive(:search).with(user_id: user_id, action: History::AUDIT_SESSION_START_EVENT, per_page: 1000).and_return(audits_from_client)
          expect(QueryAudit.client).to receive(:search).with(user_id: user_id, action: History::AUDIT_LOGIN_EVENT, per_page: 1000).and_return(nil)
          expect(QueryAudit.client).to receive(:search).with(user_id: user_id, action: History::AUDIT_SESSION_INVALIDATE_EVENT, per_page: 1000).and_return(nil)
        end

        it 'returns a list of the expected IP addresses' do
          expect(QueryAudit.ips_for_twitch_user(user_id)).to match_array(['192.168.42.82', '10.255.247.163'])
        end
      end
    end
  end
end
