class OmniauthSetup
  # OmniAuth expects the class passed to setup to respond to the #call method.
  # env - Rack environment
  def self.call(env)
    new(env).send(:setup)
  end

  # Assign variables and create a request object for use later.
  # env - Rack environment
  def initialize(env)
    @env = env
    @request = ActionDispatch::Request.new(env)
  end

  private

  # The main purpose of this method is to set the consumer key and secret.
  def setup
    university = University.find_by(subdomain: @request.subdomains.last)
    credentials = custom_credentials(university, @env['omniauth.strategy'].options.name)
    @env['omniauth.strategy'].options.merge!(credentials)
  end

  # Use the subdomain in the request to find the account with credentials
  def custom_credentials(university, provider = nil)
    case provider
      when 'linkedin'
        {
          consumer_key: university.linkedin_configuration.try(:api_key),
          consumer_secret: university.linkedin_configuration.try(:api_secret)
        }
      when 'facebook'
        {
          client_id: university.facebook_configuration.try(:app_id),
          client_secret: university.facebook_configuration.try(:app_secret)
        }
      else
        {}
    end
  end
end
