# frozen_string_literal: true

require 'rails_helper'

module Service
  describe ResponseLogger do
    let(:app) { double('app') }
    let(:env) do
      {
        method: 'my-request-method',
        url: URI.parse("https://example.com/some/path?my=query")
      }
    end
    let(:base_log_keys) { [:access_date, :latency] }
    let(:base_log) do
      {
        method: 'my-request-method',
        url_host: 'example.com',
        url_path: '/some/path',
        url_scheme: 'https',
        url_query: 'my=query'
      }
    end
    let(:l) { ResponseLogger.new(app) }

    context 'with upstream call failure' do
      before(:each) do
        expect(app).to receive(:call)
          .with(env)
          .and_raise(Faraday::ConnectionFailed.new('conn error'))
      end

      it 'should log backend_service_call_error' do
        expect(StructuredLogger).to receive(:error)
          .with(
            'backend_service_call_error',
            hash_including(
              *base_log_keys,
              :error_message,
              **base_log
            )
          )

        expect {l.call(env)}.to raise_error(Faraday::ConnectionFailed)
      end
    end

    context 'with upstream call success' do
      let(:response) do
        Faraday::Response.new.tap do |r|
          allow(r).to receive(:status).and_return(200)
        end
      end

      before(:each) do
        expect(app).to receive(:call)
          .with(env)
          .and_return(response)
      end

      it 'should log backend_service_call_success' do
        expect(StructuredLogger).to receive(:info)
          .with(
            'backend_service_call_success',
            hash_including(
              *base_log_keys,
              response_status: 200,
              **base_log
            )
          )

        expect(l.call(env)).to eq(response)
      end
    end
  end
end
