require 'oauth2'

module OpenkylinOauth::Service
  module_function

  def request(method, url, params)
    begin
      Rails.logger.info("[KylinOauth] [#{method.to_s.upcase}] #{url} || #{params}")

      client = Faraday.new(url: OpenkylinOauth.base_url)
      response = client.public_send(method, url, params)
      result = JSON.parse(response.body)

      Rails.logger.info("[KylinOauth] [#{response.status}] #{result}")

      result
    rescue Exception => e
      raise Gitlink::TipException.new(e.message)
    end
  end

  def access_token(code)
    Rails.logger.info("[KylinOauth] [code] #{code} ")
    url = "/prod-api/oauth/token?code=#{code}&client_id=#{OpenkylinOauth.client_id}&client_secret=#{OpenkylinOauth.client_secret}&redirect_uri=#{URI.encode_www_form_component(OpenkylinOauth.redirect_uri)}"
    Rails.logger.info("[KylinOauth] [url] #{url} ")
    client = Faraday.new(url: OpenkylinOauth.base_url)
    response = client.public_send(:get, url)
    Rails.logger.info("[KylinOauth] [response.body] #{response.body} ")
    result = JSON.parse(response.body)
    result
  end

  def user_info(access_token)
    request(:get, '/prod-api/getOAuthInfo', { access_token: access_token })
  end
end