# frozen_string_literal: true

module Twitch
  class Route
    attr_accessor :path, :location, :backend, :skip_backend_check
    attr_writer :status

    ROUTE_FIELDS = %i[path status location backend].freeze
    ROUTE_FIELDS.each do |field|
      attr_accessor field
    end

    def initialize(path, *args)
      @path = path

      return unless (params = args[0])
      raise 'Invalid route parameter format. Must be provided as key => value pairs.' unless params.is_a?(Hash)
      params.each do |field, value|
        send(:"#{field.to_s}=", value) if respond_to?(field)
      end
    end

    def status
      @status || 200
    end

    class << self
      def list
        @routes ||= []
      end

      def add(path, *args)
        route = Twitch::Route.new(path, *args)
        list.push(route)
      end

      def actual_backend(res)
        return :legacy if res.headers['X-MH-Cache'] || \
                          /^(1\.1 varnish, )+1\.1 varnish$/ =~ res.headers['via'] || \
                          res.headers['server'].casecmp('varnish').zero?
        return :cloudfront if res.headers['X-Amz-Cf-Id']
        return :s3 if res.headers['server'] == 'AmazonS3'
        :twilight # default is twilight. no reliable way to specifically ID twilight
      end
    end
  end
end

def route(*args)
  Twitch::Route.add(*args)
end
