require 'oauth2'

module Ci4s::Service
  module_function

  def client_id
    config = Rails.application.config_for(:configuration)
    config.dig("oauth", "ci4s", "client_id")
  end
  
  def client_secret
    config = Rails.application.config_for(:configuration)
    config.dig("oauth", "ci4s", "client_secret")
  end
  
  def base_url
    config = Rails.application.config_for(:configuration)
    config.dig("oauth", "ci4s", "base_url")
  end
  
  def redirect_uri
    config = Rails.application.config_for(:configuration)
    config.dig("oauth", "ci4s", "redirect_uri")
  end

  def oauth_url
    "#{base_url}/oauth/authorize?client_id=#{client_id}&redirect_uri=#{URI.encode_www_form_component(redirect_uri)}&response_type=code&grant_type=authorization_code"
  end

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

      client ||= begin
                   Faraday.new(url: 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
                 end
      response = client.public_send(method, url, params)
      result = JSON.parse(response.body)

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

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

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

  def user_info(access_token)
    request(:get, '/user/info', {access_token: access_token})
  end
end