package cn.qihangerp.erp.support;

import cn.qihangerp.model.request.ExternalGoodsUpsertRequest;
import cn.qihangerp.model.request.ExternalGoodsPddQuantityUpdateRequest;
import cn.qihangerp.model.request.ExternalPddGoodsDetailRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 对外商品接口请求日志脱敏：{@code pddPopAuth} 中 appSecret 全掩、appKey/accessToken 首尾保留便于排障。
 *
 * @author guochengyu
 */
public final class ExternalGoodsRequestLogSupport {

    private ExternalGoodsRequestLogSupport() {
    }

    /**
     * {@link ExternalGoodsPddQuantityUpdateRequest} 脱敏日志（不修改入参）。
     */
    public static String goodsPddQuantityUpdateRequestJsonForLog(ExternalGoodsPddQuantityUpdateRequest req) {
        if (req == null) {
            return "null";
        }
        try {
            JSONObject root = JSON.parseObject(JSON.toJSONString(req));
            if (root == null) {
                return "{}";
            }
            JSONObject auth = root.getJSONObject("pddPopAuth");
            if (auth != null && !auth.isEmpty()) {
                maskPddPopAuth(auth);
            }
            return root.toJSONString();
        } catch (Exception e) {
            return "{\"_logSanitizeError\":true}";
        }
    }

    /**
     * {@link ExternalPddGoodsDetailRequest} 脱敏日志（不修改入参）。
     */
    public static String pddDetailRequestJsonForLog(ExternalPddGoodsDetailRequest req) {
        if (req == null) {
            return "null";
        }
        try {
            JSONObject root = JSON.parseObject(JSON.toJSONString(req));
            if (root == null) {
                return "{}";
            }
            JSONObject auth = root.getJSONObject("pddPopAuth");
            if (auth != null && !auth.isEmpty()) {
                maskPddPopAuth(auth);
            }
            return root.toJSONString();
        } catch (Exception e) {
            return "{\"_logSanitizeError\":true}";
        }
    }

    /**
     * 序列化为 JSON 并对 {@link ExternalGoodsUpsertRequest#getPddPopAuth()} 脱敏（不修改入参对象）。
     */
    public static String upsertRequestJsonForLog(ExternalGoodsUpsertRequest req) {
        if (req == null) {
            return "null";
        }
        try {
            JSONObject root = JSON.parseObject(JSON.toJSONString(req));
            if (root == null) {
                return "{}";
            }
            JSONObject auth = root.getJSONObject("pddPopAuth");
            if (auth != null && !auth.isEmpty()) {
                maskPddPopAuth(auth);
            }
            JSONObject sphAuth = root.getJSONObject("sphPopAuth");
            if (sphAuth != null && !sphAuth.isEmpty()) {
                maskPddPopAuth(sphAuth);
            }
            return root.toJSONString();
        } catch (Exception e) {
            return "{\"_logSanitizeError\":true}";
        }
    }

    private static void maskPddPopAuth(JSONObject auth) {
        replaceSecret(auth, "appKey", 4, 4);
        replaceSecret(auth, "appSecret", 0, 0);
        replaceSecret(auth, "accessToken", 4, 4);
    }

    /**
     * @param keepHead keepTail 均为 0 时表示整段替换为 {@code ***}（用于 appSecret）
     */
    private static void replaceSecret(JSONObject auth, String field, int keepHead, int keepTail) {
        if (!auth.containsKey(field)) {
            return;
        }
        String raw = auth.getString(field);
        if (!StringUtils.hasText(raw)) {
            return;
        }
        if (keepHead == 0 && keepTail == 0) {
            auth.put(field, "***");
            return;
        }
        auth.put(field, maskKeepEnds(raw, keepHead, keepTail));
    }

    private static String maskKeepEnds(String s, int head, int tail) {
        if (!StringUtils.hasText(s)) {
            return s;
        }
        if (head < 0) {
            head = 0;
        }
        if (tail < 0) {
            tail = 0;
        }
        if (s.length() <= head + tail) {
            return "***";
        }
        return s.substring(0, head) + "***" + s.substring(s.length() - tail);
    }
}
