# frozen_string_literal: true

require_relative 'bootstrap'
require 'minitest/autorun'

# Test that cookie and query string overrides work for www => beta redirect
class MobileRedirectTest < Minitest::Test
  @@protocols = %i[http https].freeze
  @@twitch = @@protocols.map { |protocol| [protocol, Twitch::Web.create(protocol)] }.to_h

  def teardown
    sleep 0.5
  end

  def test_mobile_redirect
    @@protocols.each do |protocol|
      5.times do
        res = @@twitch[protocol].get('/') do |req|
          req.headers[:user_agent] = MOBILE_USER_AGENT
        end
        assert_equal res.status, 302
        assert_equal res.headers['location'], "#{protocol}://m.twitch.tv/?desktop-redirect=true"
        sleep 0.5
      end
    end
  end

  def test_no_mobile_redirect_with_opt_out_cookie
    res = @@twitch[:https].get('/') do |req|
      req.headers[:user_agent] = MOBILE_USER_AGENT
      req.headers['Cookie'] = 'mobile_opt_out=true'
    end
    if res.status == 302
      refute_includes res.headers['location'], 'm.twitch.tv'
    else
      assert_equal res.status, 200, "Unexpected response of #{res.status}"
    end
  end

  def test_no_mobile_redirect_with_opt_out_query_string
    res = @@twitch[:https].get('/') do |req|
      req.headers[:user_agent] = MOBILE_USER_AGENT
      req.params['no-mobile-redirect'] = 'true'
    end
    if res.status == 302
      refute_includes res.headers['location'], 'm.twitch.tv'
    else
      assert_equal res.status, 200, "Unexpected response of #{res.status}"
    end
  end

  MOBILE_PATH_BLACKLIST.each do |data|
    define_method :"test_no_mobile_redirect_on_#{data[:path].gsub('/', '__')}" do
      res = @@twitch[:https].get(data[:path]) do |req|
        req.headers[:user_agent] = MOBILE_USER_AGENT
      end
      assert_equal data[:status], res.status, "Unexpected response of #{res.status} on #{data[:path]}, expected #{data[:status]}"
      refute_includes res.headers['location'], 'm.twitch.tv' if [301, 302].include?(data[:status])
    end
  end
end
