package com.malk.service.integration.impl;

import com.malk.server.integration.INTPConf;
import com.malk.server.integration.INTPR;
import com.malk.service.integration.INTPClient_User;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class INTPImplClient_User implements INTPClient_User {

    @Autowired
    private INTPConf intpConf;

    @Override
    public String getAccessToken() {
        String key = "token:" + intpConf.getClientId();
        String cached = UtilToken.get(INTPConf.NS, key);
        if (StringUtils.isNotBlank(cached)) {
            return cached;
        }
        // ppExt: OAuth2 token endpoint 走 form-urlencoded，不是 JSON body
        Map form = UtilMap.map("grant_type, client_id, client_secret",
                "client_credentials", intpConf.getClientId(), intpConf.getClientSecret());
        INTPR r = (INTPR) UtilHttp.doPost(intpConf.getBaseUrl() + INTPConf.PATH_TOKEN,
                null, null, null, form, INTPR.class);
        // fixme: expires_in 通常 7200s；提前 60s 失效，UtilToken.put 内部还会再扣 5s
        long ttlMillis = (long) (r.getExpires_in() - INTPConf.TOKEN_AHEAD_SECONDS) * 1000L;
        UtilToken.put(INTPConf.NS, key, r.getAccess_token(), ttlMillis);
        return r.getAccess_token();
    }

    @Override
    public Map createUser(String access_token, String username, String password, Map body_ext) {
        Map header = UtilMap.map("Authorization", "Bearer " + access_token);
        Map body = UtilMap.map("username, password", username, password);
        if (body_ext != null) {
            body.putAll(body_ext);
        }
        return (Map) INTPR.doPost(intpConf.getBaseUrl() + INTPConf.PATH_USERS, header, null, body).getData();
    }

    @Override
    public Boolean updateUser(String access_token, String username, Map body_ext) {
        Map header = UtilMap.map("Authorization", "Bearer " + access_token);
        // ppExt: username 走 Query Param 而非 Path（apifox 文档原样保留）
        Map param = UtilMap.map("username", username);
        Map body = body_ext != null ? body_ext : new HashMap();
        INTPR r = (INTPR) UtilHttp.doPatch(intpConf.getBaseUrl() + INTPConf.PATH_USER,
                header, param, body, INTPR.class);
        return r.isResult();
    }

    @Override
    public Boolean deleteUsers(String access_token, List<String> usernames) {
        Map header = UtilMap.map("Authorization", "Bearer " + access_token);
        // ppExt: HTTP 方法是 POST 而非 DELETE（因 body 需带数组）
        Map body = UtilMap.map("usernames", usernames);
        return INTPR.doPost(intpConf.getBaseUrl() + INTPConf.PATH_USERS_DELETE, header, null, body).isResult();
    }

    @Override
    public Map queryUsers(String access_token, Map query) {
        Map header = UtilMap.map("Authorization", "Bearer " + access_token);
        return (Map) INTPR.doGet(intpConf.getBaseUrl() + INTPConf.PATH_USERS, header, query).getData();
    }
}
