package com.malk.service.eiam.impl;

import com.alibaba.fastjson.JSON;
import com.malk.server.eiam.EiamConf;
import com.malk.server.eiam.EiamTokenResponse;
import com.malk.service.eiam.EiamClient;
import com.malk.utils.UtilHttp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * EIAM DeveloperAPI OIDC 原子接口实现。
 */
@Service
public class EiamClientImpl implements EiamClient {

    @Autowired
    private EiamConf eiamConf;

    @Override
    public EiamTokenResponse generateToken(String instanceId, String applicationId, String grantType,
                                           String clientId, String clientSecret,
                                           Map<String, Object> bodyExt) {
        Map<String, Object> form = bodyExt == null
                ? new HashMap<>() : new HashMap<>(bodyExt);
        form.put("grant_type", grantType);
        form.put("client_id", clientId);
        form.put("client_secret", clientSecret);
        String url = eiamConf.getBaseUrl() + "/v2/" + instanceId + "/" + applicationId + "/oauth2/token";
        String response = UtilHttp.doPost(url, null, null, null, form);
        return JSON.parseObject(response, EiamTokenResponse.class);
    }
}
