require 'oauth2'

module GitlinkOauth::Service
  module_function

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

      # client = Faraday.new(url: GitlinkOauth.base_url)
      client = Faraday.new(url: GitlinkOauth.base_url) do |req|
        req.request :url_encoded
        req.headers['Content-Type'] = 'application/json'
        req.response :logger # 显示日志
        req.adapter Faraday.default_adapter
        req.authorization :Bearer, params[:access_token]
        req.headers['Authorization']
      end
      response = client.public_send(method, url, params)
      result = JSON.parse(response.body)

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

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

  def access_token(code)
    begin
      Rails.logger.info("[GitlinkOauth] [code] #{code} ")
      Rails.logger.info("[GitlinkOauth] [redirect_uri] #{GitlinkOauth.redirect_uri} ")
      client = OAuth2::Client.new(GitlinkOauth.client_id, GitlinkOauth.client_secret, site: GitlinkOauth.base_url)
      result = client.auth_code.get_token(code, redirect_uri: GitlinkOauth.redirect_uri).to_hash
      return result
    rescue Exception => e
      raise Gitlink::TipException.new(e.message)
    end
  end

  def user_info(access_token)
    request(:get, '/api/users/me.json', {access_token: access_token})
  end
end