package com.hotent.base.conf;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hotent.base.util.RestAesUtil;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author 梁宏锦
 * @date 2025/07/08
 **/
public class DecryptingDecoder implements Decoder {
    private final Decoder decoder;
    private final boolean securityEnabled;

    public DecryptingDecoder(boolean securityEnabled, ObjectFactory<HttpMessageConverters> messageConverters) {
        this.decoder = new SpringDecoder(messageConverters);
        this.securityEnabled = securityEnabled;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, feign.FeignException {
        if (!securityEnabled) {
            // 如果解密功能未开启，则直接使用原始decoder解析响应
            return decoder.decode(response, type);
        }

        // 先读取原始响应体内容
        String encryptedBody = Util.toString(response.body().asReader());

        // 在这里做解密逻辑，例如：
        String decryptedBody = decrypt(encryptedBody);

        // 构造一个新的 Response 对象，替换 body 内容为解密后的字符串
        Response modifiedResponse = response.toBuilder()
                .body(decryptedBody.getBytes(java.nio.charset.StandardCharsets.UTF_8))
                .build();

        // 使用原始 decoder 解析修改后的响应
        return decoder.decode(modifiedResponse, type);
    }

    private String decrypt(String encryptedData) {
        if(JSONUtil.isJson(encryptedData)) {
            if(JSONUtil.isJsonArray(encryptedData)){
                return encryptedData;
            }
            JSONObject obj = JSONUtil.parseObj(encryptedData);
            String val = obj.getStr("value");
            String encrypted = obj.getStr("encrypted");
            if("true".equals(encrypted)) {
                // 这里写你的具体解密逻辑，例如 AES 解密
                return RestAesUtil.getInstance().decrypt(val);
            } else {
                return encryptedData;
            }
        } else {
            return encryptedData;
        }


    }
}