# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

require_relative 'set_up'

# The endpoints of this test run. The defaults are deliberately next to, but
#   never on, the ports of a development stack (3000 and 6042), so that a suite
#   can run while the app of this checkout is up. Set the variables to run two
#   suites side by side.
CAPYBARA_PORT = ENV.fetch('CAPYBARA_PORT', 3001).to_i
CAPYBARA_HOSTNAME = ENV['CAPYBARA_HOSTNAME'] || (ENV['CI'].present? ? 'build' : 'localhost')
WS_PORT = ENV.fetch('WS_PORT', 6043).to_i

RSpec.configure do |config|

  # Provide SSL certificates with the help of the 'localhost' gem.
  localhost_authority = Localhost::Authority.new(CAPYBARA_HOSTNAME, issuer: nil)
  localhost_authority.save # make sure the certificate is created

  Capybara.register_server :puma_wrapper do |app, port, host, **_options|
    # Start a silenced Puma as application server.
    Capybara.servers[:puma].call(app, port, host, Silent: true, Host: "ssl://0.0.0.0?key=#{localhost_authority.key_path}&cert=#{localhost_authority.certificate_path}", Threads: '0:16')
  end

  Capybara.configure do |capybara_config|
    capybara_config.server      = :puma_wrapper
    capybara_config.server_port = CAPYBARA_PORT
    capybara_config.save_path   = 'tmp/screenshots'

    # See https://docs.gitlab.com/runner/executors/docker.html#create-a-network-for-each-job
    capybara_config.app_host = "https://#{CAPYBARA_HOSTNAME}"
  end

  config.before(:each, type: :system) do |example|

    Setting.set('http_type', 'https')
    Setting.set('fqdn', "#{CAPYBARA_HOSTNAME}:#{CAPYBARA_PORT}")

    # Outside of production 'websocket_backend' is 'websocketPort', so the legacy
    #   frontend takes the websocket port from this setting - it has to follow the
    #   port websocket_server.rb actually listens on.
    Setting.set('websocket_port', WS_PORT.to_s)

    browser_name = ENV.fetch('TEST_BROWSER', 'chromium')

    # If mobile user agent was requested by the example,
    #   use an appropriate driver (e.g. zammad_chromium_mobile).
    if example.metadata[:mobile_user_agent].present?
      browser_name += '_mobile'

      # End the Capybara browser session whenever the user agent is to be mocked,
      #   in order to get a fresh session for subsequent examples.
      Capybara.send(:session_pool).reverse_each do |_mode, session|
        PlaywrightSessionQuit.call(session)
        session.quit
      end
    end

    # set custom Zammad driver (e.g. zammad_chromium) for special
    # functionalities and CI requirements
    driven_by(:"zammad_#{browser_name}")

    screen_size = example.metadata[:screen_size] || case example.metadata[:app]
                                                    when :mobile
                                                      :mobile
                                                    when :desktop_view
                                                      :desktop_view
                                                    else
                                                      :desktop
                                                    end

    case screen_size
    when :mobile
      browser_width  = 390
      browser_height = 844
    when :tablet
      browser_width  = 1020
      browser_height = 760
    else # :desktop
      browser_width  = 1520
      browser_height = 1000
    end

    page.current_window.resize_to(browser_width, browser_height)

    # Remember the size so that additional sessions (see CommonActions#using_session)
    #   can be brought to the same size - their windows otherwise keep the driver's
    #   small default size.
    @zammad_browser_window_size = [browser_width, browser_height]
  end

  capybara_examples_performed = 0

  config.after(:each, type: :system) do |example|
    capybara_examples_performed += 1
    # End the main capybara session only from time to time, to speed up tests and make
    #   sure memory consumption does not rise too much.
    # Also end the session whenever the user agent was mocked, in order to get a fresh
    #   session for subsequent examples.
    # Make sure additional sessions (from using_sessions) are always ended
    #   after every test and not kept alive.
    Capybara.send(:session_pool).reverse_each do |_mode, session|
      next if session.eql?(Capybara.current_session) && (capybara_examples_performed % 100).nonzero? && !example.metadata[:mobile_user_agent]

      PlaywrightSessionQuit.call(session)

      # session.quit is a real browser call with no timeout of its own - specs
      #   using multiple sessions (e.g. chat_spec.rb's using_session :customer) have been
      #   observed stalling the whole suite for 18+ minutes when it hangs. Bound it so a
      #   stuck session delays things by seconds instead.
      Timeout.timeout(10) { session.quit }
    rescue Timeout::Error
      Rails.logger.error "Timed out quitting Capybara session #{session.inspect}"

      # Session#quit sets @driver (and @document) to nil only *after* @driver.quit returns -
      #   if that call is the one that hung and got interrupted above, those ivars are never
      #   reset. Session#driver then lazily recreates a driver only when @driver is nil, so
      #   without this, the next example to touch this session would silently keep reusing
      #   the broken driver instead of getting a fresh one.
      session.instance_variable_set(:@driver, nil)
      session.instance_variable_set(:@document, nil)
    end
  end

  retry_exceptions = [
    Net::OpenTimeout,
    Net::ReadTimeout,
  ].freeze

  config.around(:each, type: :system) do |example|
    use_vcr = example.metadata.fetch(:use_vcr, false)

    WebMock.disable! if !use_vcr
    # rspec-retry
    example.run_with_retry retry: 3, exceptions_to_retry: retry_exceptions
    WebMock.enable! if !use_vcr
  end
end
