package com.jeesharp.business.modules.finance.api.support;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;

/**
 * 微信支付 V3 回调解密报文字段解析工具（无 Spring 依赖，供网关与财务模块共用）。
 *
 * @author jeesharp
 * @since 2026-06-13
 */
public final class WechatPayNotifyParseSupport {

    private WechatPayNotifyParseSupport() {
    }

    /**
     * 解析微信 V3 解密报文中的成功支付时间（{@code success_time}），解析失败返回 {@code null}。
     */
    public static LocalDateTime parseSuccessTime(Object successTimeRaw) {
        if (successTimeRaw == null) {
            return null;
        }
        String s = String.valueOf(successTimeRaw).trim();
        if (s.isEmpty()) {
            return null;
        }
        try {
            return OffsetDateTime.parse(s).toLocalDateTime();
        } catch (DateTimeParseException ignored) {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static BigDecimal parseTotalAmountYuan(Map<String, Object> decrypted) {
        if (decrypted == null) {
            return null;
        }
        BigDecimal direct = parseAmountTotalYuanFromMap(decrypted.get("amount"));
        if (direct != null) {
            return direct;
        }
        Object subOrdersRaw = decrypted.get("sub_orders");
        if (!(subOrdersRaw instanceof List<?> list) || list.isEmpty()) {
            return null;
        }
        long sumFen = 0L;
        for (Object item : list) {
            if (item instanceof Map<?, ?> sub) {
                BigDecimal subYuan = parseAmountTotalYuanFromMap(sub.get("amount"));
                if (subYuan != null) {
                    sumFen += subYuan.movePointRight(2).longValue();
                }
            }
        }
        return sumFen > 0 ? BigDecimal.valueOf(sumFen).movePointLeft(2) : null;
    }

    @SuppressWarnings("unchecked")
    private static BigDecimal parseAmountTotalYuanFromMap(Object amountObj) {
        if (!(amountObj instanceof Map)) {
            return null;
        }
        Map<String, Object> amount = (Map<String, Object>) amountObj;
        Object total = amount.get("total");
        if (total == null) {
            return null;
        }
        long fen;
        if (total instanceof Number) {
            fen = ((Number) total).longValue();
        } else {
            try {
                fen = Long.parseLong(String.valueOf(total));
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return BigDecimal.valueOf(fen).movePointLeft(2);
    }
}
