package com.malk.service.eiam.impl;

import com.alibaba.fastjson.JSON;
import com.malk.server.common.McException;
import com.malk.server.eiam.EiamApiResponse;
import com.malk.server.eiam.EiamConf;
import com.malk.service.eiam.EiamClient_User;
import com.malk.utils.UtilHttp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * EIAM DeveloperAPI 账户管理原子接口实现。
 */
@Service
public class EiamClient_UserImpl implements EiamClient_User {

    @Autowired
    private EiamConf eiamConf;

    @Override
    public EiamApiResponse createUser(String accessToken, String instanceId, String applicationId,
                                      String username, String primaryOrganizationalUnitId,
                                      Map<String, Object> bodyExt) {
        Map<String, Object> body = bodyExt == null
                ? new HashMap<>() : new HashMap<>(bodyExt);
        body.put("username", username);
        body.put("primaryOrganizationalUnitId", primaryOrganizationalUnitId);
        String response = UtilHttp.doPost(usersUrl(instanceId, applicationId),
                headers(accessToken), null, body);
        return parseResponse(response);
    }

    @Override
    public EiamApiResponse patchUser(String accessToken, String instanceId, String applicationId,
                                     String userId, Map<String, Object> bodyExt) {
        Map<String, Object> body = bodyExt == null
                ? new HashMap<>() : new HashMap<>(bodyExt);
        String response = UtilHttp.doPatch(userUrl(instanceId, applicationId, userId),
                headers(accessToken), null, body);
        // prd PatchUser 成功时可能返回 204/空响应体，HTTP 层未抛异常即视为成功。
        return parseActionResponse(response);
    }

    @Override
    public EiamApiResponse setUserPrimaryOrganizationalUnit(String accessToken, String instanceId,
                                                            String applicationId, String userId,
                                                            String organizationalUnitId) {
        Map<String, Object> body = new HashMap<>();
        body.put("organizationalUnitId", organizationalUnitId);
        String url = userUrl(instanceId, applicationId, userId)
                + "/actions/setUserPrimaryOrganizationalUnit";
        String response = UtilHttp.doPost(url, headers(accessToken), null, body);
        return parseActionResponse(response);
    }

    @Override
    public EiamApiResponse addUserToOrganizationalUnits(String accessToken, String instanceId,
                                                        String applicationId, String userId,
                                                        List<String> organizationalUnitIds) {
        Map<String, Object> body = new HashMap<>();
        body.put("organizationalUnitIds", organizationalUnitIds);
        String url = userUrl(instanceId, applicationId, userId)
                + "/actions/addUserToOrganizationalUnits";
        String response = UtilHttp.doPost(url, headers(accessToken), null, body);
        return parseActionResponse(response);
    }

    @Override
    public EiamApiResponse deleteUser(String accessToken, String instanceId, String applicationId,
                                      String userId) {
        String response = UtilHttp.doDelete(userUrl(instanceId, applicationId, userId),
                headers(accessToken), null, (Map) null);
        return parseResponse(response);
    }

    /**
     * 将 EIAM 写接口响应转换为统一对象，屏蔽第三方非 JSON 响应导致的解析器异常。
     *
     * @param response EIAM 原始响应
     * @return EIAM 响应对象
     */
    static EiamApiResponse parseResponse(String response) {
        if (response == null || response.trim().isEmpty()) {
            throw new McException("EIAM_EMPTY_RESPONSE", "EIAM 响应为空");
        }
        try {
            EiamApiResponse payload = JSON.parseObject(response, EiamApiResponse.class);
            if (payload == null) {
                throw new McException("EIAM_INVALID_RESPONSE", "EIAM 响应格式错误");
            }
            return payload;
        } catch (McException ex) {
            throw ex;
        } catch (RuntimeException ex) {
            // fixme 第三方偶发返回纯文本时，不暴露原始响应，也不让 Fastjson 语法异常泄漏到业务层。
            throw new McException("EIAM_INVALID_RESPONSE", "EIAM 响应不是有效 JSON，请按账户名核对实际落库状态");
        }
    }

    /**
     * 解析无响应体的 EIAM 动作接口；HTTP 层未抛异常即视为成功。
     *
     * @param response EIAM 原始响应
     * @return EIAM 响应对象
     */
    static EiamApiResponse parseActionResponse(String response) {
        if (response == null || response.trim().isEmpty()) {
            return new EiamApiResponse();
        }
        return parseResponse(response);
    }

    private Map<String, String> headers(String accessToken) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + accessToken);
        headers.put("Content-Type", "application/json");
        return headers;
    }

    private String usersUrl(String instanceId, String applicationId) {
        return eiamConf.getBaseUrl() + "/v2/" + instanceId + "/" + applicationId + "/users";
    }

    private String userUrl(String instanceId, String applicationId, String userId) {
        return usersUrl(instanceId, applicationId) + "/" + userId;
    }
}
