# frozen_string_literal: true

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

require File.expand_path('../../spec_helper', __dir__)

module Selenium
  module WebDriver
    module Remote
      module Http
        describe Common do
          let(:client_config) { ClientConfig.new }

          subject(:common) do
            common = described_class.new(client_config: client_config)
            common.server_url = URI.parse('http://server')
            allow(common).to receive(:request)

            common
          end

          after do
            ClientConfig.default_extra_headers = nil
            ClientConfig.default_user_agent = nil
          end

          it 'sends non-empty body header for POST requests without command data' do
            common.call(:post, 'clear', nil)

            expect(common).to have_received(:request)
              .with(:post, URI.parse('http://server/clear'),
                    hash_including('Content-Length' => '2'), '{}')
          end

          it 'sends a standard User-Agent by default' do
            user_agent_regexp = %r{\Aselenium/#{WebDriver::VERSION} \(ruby #{Platform.os}\)\z}

            common.call(:post, 'session', nil)

            expect(common).to have_received(:request)
              .with(:post, URI.parse('http://server/session'),
                    hash_including('User-Agent' => a_string_matching(user_agent_regexp)), '{}')
          end

          context 'when the client config registers extra headers' do
            let(:client_config) { ClientConfig.new(extra_headers: {'Foo' => 'bar'}) }

            it 'sends them' do
              common.call(:post, 'session', nil)

              expect(common).to have_received(:request)
                .with(:post, URI.parse('http://server/session'),
                      hash_including('Foo' => 'bar'), '{}')
            end
          end

          context 'when the client config overrides the User-Agent' do
            let(:client_config) { ClientConfig.new(user_agent: 'rspec/1.0 (ruby 3.2)') }

            it 'uses it' do
              common.call(:post, 'session', nil)

              expect(common).to have_received(:request)
                .with(:post, URI.parse('http://server/session'),
                      hash_including('User-Agent' => 'rspec/1.0 (ruby 3.2)'), '{}')
            end
          end

          it 'still honors the Http::Common.user_agent= setter' do
            described_class.user_agent = 'rspec/1.0 (ruby 3.2)'

            common.call(:post, 'session', nil)

            expect(common).to have_received(:request)
              .with(:post, URI.parse('http://server/session'),
                    hash_including('User-Agent' => 'rspec/1.0 (ruby 3.2)'), '{}')
          end

          context 'when encoding strings to UTF-8' do
            it 'converts binary-encoded strings that are valid UTF-8' do
              binary_string = +'return navigator.userAgent;'
              binary_string.force_encoding(Encoding::BINARY)
              command_hash = {script: binary_string, args: []}

              common.call(:post, 'execute', command_hash)

              expect(common).to have_received(:request) do |_verb, _url, _headers, payload|
                expect { JSON.parse(payload) }.not_to raise_error
                parsed = JSON.parse(payload)
                expect(parsed['script']).to eq('return navigator.userAgent;')
                expect(parsed['script'].encoding).to eq(Encoding::UTF_8)
              end
            end

            it 'converts binary-encoded strings in nested hashes' do
              binary_string = +'test value'
              binary_string.force_encoding(Encoding::BINARY)
              command_hash = {
                outer: {
                  inner: binary_string,
                  another: 'utf8 string'
                }
              }

              common.call(:post, 'test', command_hash)

              expect(common).to have_received(:request) do |_verb, _url, _headers, payload|
                expect { JSON.parse(payload) }.not_to raise_error
                parsed = JSON.parse(payload)
                expect(parsed['outer']['inner']).to eq('test value')
              end
            end

            it 'converts binary-encoded strings in arrays' do
              binary_string = +'array item'
              binary_string.force_encoding(Encoding::BINARY)
              command_hash = {items: [binary_string, 'utf8 item']}

              common.call(:post, 'test', command_hash)

              expect(common).to have_received(:request) do |_verb, _url, _headers, payload|
                expect { JSON.parse(payload) }.not_to raise_error
                parsed = JSON.parse(payload)
                expect(parsed['items']).to eq(['array item', 'utf8 item'])
              end
            end

            it 'raises error for invalid byte sequences' do
              # Create an invalid UTF-8 byte sequence
              invalid_string = +"\xFF\xFE"
              invalid_string.force_encoding(Encoding::BINARY)
              command_hash = {script: invalid_string}

              expect { common.call(:post, 'execute', command_hash) }
                .to raise_error(WebDriver::Error::WebDriverError, /Unable to encode string to UTF-8/)
            end

            it 'handles already UTF-8 encoded strings' do
              utf8_string = 'already utf-8'
              command_hash = {script: utf8_string}

              common.call(:post, 'execute', command_hash)

              expect(common).to have_received(:request) do |_verb, _url, _headers, payload|
                expect { JSON.parse(payload) }.not_to raise_error
                parsed = JSON.parse(payload)
                expect(parsed['script']).to eq('already utf-8')
              end
            end
          end
        end
      end # Http
    end # Remote
  end # WebDriver
end # Selenium
