package com.jeesharp.business.modules.pay.paysubmerchantapplyment.support;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.entity.PaySubMerchantApplyment;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.enums.PaySubMerchantApplyLocalStatusEnum;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.enums.PaySubMerchantApplyStatusEnum;

/**
 * 特约商户进件状态归一化与「有效二级商户」判定，供 application / service 层共用。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
public final class PaySubMerchantApplyStatusSupport {

    /** 微信进件审核完成（本地归一化状态码） */
    public static final String APPLY_STATUS_FINISH = "FINISH";

    private PaySubMerchantApplyStatusSupport() {
    }

    /**
     * 是否为有效二级商户：已分配 sub_mchid、进件 FINISH、未注销。
     */
    public static boolean isEffectiveSubMerchant(PaySubMerchantApplyment applyment) {
        if (applyment == null) {
            return false;
        }
        if (PaySubMerchantApplyStatusEnum.SUB_MCH_CANCELLED.getValue().equals(applyment.getApplyStatus())) {
            return false;
        }
        if (StrUtil.isBlank(applyment.getSubMchId())) {
            return false;
        }
        return APPLY_STATUS_FINISH.equals(normalizeApplyStatus(applyment.getApplyStatus()));
    }

    /**
     * 进件状态归一化（兼容微信 {@code APPLYMENT_STATE_*} 前缀与本地简写）。
     */
    public static String normalizeApplyStatus(String applyStatus) {
        if (StrUtil.isBlank(applyStatus)) {
            return "";
        }
        String upper = applyStatus.trim().toUpperCase();
        return switch (upper) {
            case "APPLYMENT_STATE_EDITTING" -> PaySubMerchantApplyLocalStatusEnum.DRAFT.getValue();
            case "APPLYMENT_STATE_AUDITING" -> "AUDITING";
            case "APPLYMENT_STATE_REJECTED" -> "REJECTED";
            case "APPLYMENT_STATE_TO_BE_CONFIRMED" -> "ACCOUNT_NEED_VERIFY";
            case "APPLYMENT_STATE_TO_BE_SIGNED", "APPLYMENT_STATE_SIGNING" -> "NEED_SIGN";
            case "APPLYMENT_STATE_FINISHED" -> APPLY_STATUS_FINISH;
            case "APPLYMENT_STATE_CANCELED", "APPLYMENT_STATE_CANCELLED" -> "CANCELED";
            case "APPLYMENT_STATE_FROZEN" -> "FROZEN";
            default -> upper.startsWith("APPLYMENT_STATE_")
                    ? upper.substring("APPLYMENT_STATE_".length())
                    : applyStatus.trim();
        };
    }

    /**
     * 微信查询/回调 {@code applyment_state} 归一化为库内统一状态码（空白原样返回）。
     */
    public static String normalizeWxApplymentState(String state) {
        if (StrUtil.isBlank(state)) {
            return state;
        }
        return normalizeApplyStatus(state);
    }
}
