package org.eco.common.core.exception;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;

import java.io.Serial;
import java.text.MessageFormat;

/**
 * 业务异常
 *
 * @author wgk
 */
public final class BusinessException extends RuntimeException {
    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 错误码
     */
    @Getter
    private Integer code;

    /**
     * 错误参数
     */
    private Object[] msgParams;

    /**
     * 错误明细，内部调试错误
     */
    private String message;

    /**
     * 空构造方法，避免反序列化问题
     */
    public BusinessException() {
    }

    public BusinessException(String message) {
        this.message = message;
    }

    public BusinessException(String message, Integer code) {
        this.message = message;
        this.code = code;
    }

    public BusinessException(Integer code, String msg, Object... msgParams) {
        this.message = msg;
        this.code = code;
        this.msgParams = msgParams;
    }

    public BusinessException(String msg, Object... msgParams) {
        this.message = msg;
        this.msgParams = msgParams;
    }

    @Override
    public String getMessage() {
        if (StrUtil.isNotBlank(message)) {
            if (msgParams != null && msgParams.length > 0) {
                return MessageFormat.format(message, msgParams);
            }
        }
        return message; // 如果不传参数，直接返回
    }

    public BusinessException setMessage(String message) {
        this.message = message;
        return this;
    }

}
