module HuaweiCloud
  class ImaAccount
    IAM_TOKEN_KEY = "huaweicloud:iam_token".freeze
    CONFIG = Rails.application.config_for(:configuration)['huawei_code_check']
    PROJECT_ID = CONFIG['project_id']
    REGION = CONFIG['region']
    DOMAIN_NAME = CONFIG['domain_name']
    USER_NAME = CONFIG['user_name']
    USER_PASSWORD = CONFIG['user_password']

    def initialize
      @region = REGION
      @domain_name = DOMAIN_NAME
      @user_name = USER_NAME
      @user_password = USER_PASSWORD
      @project_id = PROJECT_ID
    end

    # 获取或缓存 Token
    def token
      cached = Rails.cache.fetch(IAM_TOKEN_KEY)
      return cached if cached

      new_token = fetch_token
      Rails.cache.write(IAM_TOKEN_KEY,new_token,expires_in: 23.hour)
      new_token
    end
    private

    def fetch_token
      url = "https://iam.#{@region}.myhuaweicloud.com/v3/auth/tokens"
      body = {
        auth: {
          identity: {
            methods: ["password"],
            password: {
              user: {
                domain: { name: @domain_name },
                name: @user_name,
                password: @user_password
              }
            }
          },
          scope: {
            project: { id: @project_id }
          }
        }
      }
      uri = URI.parse(url)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = (uri.scheme == "https")
      request = Net::HTTP::Post.new(uri.request_uri)
      request["Content-Type"] = "application/json;charset=utf8"
      request.content_type = "application/json"
      request.body = body.to_json
      response = http.request(request)
      token = response["x-subject-token"]
      raise "Failed to obtain IAM token" unless token
      token
    rescue => e
      raise "IAM token fetch failed: #{response}"
    end
  end
end