using QYZH.InteractiveMagazine.Models.Dto;

namespace QYZH.InteractiveMagazine.Models.Common;

/// <summary>
/// 业务异常类
/// </summary>
public class BusinessException : Exception
{
    /// <summary>
    /// 错误码
    /// </summary>
    public int Code { get; set; }

    /// <summary>
    /// 业务状态码
    /// </summary>
    public ResultCode ResultCode { get; set; } = ResultCode.FAIL;

    /// <summary>
    /// 无参构造函数
    /// </summary>
    public BusinessException() : base()
    {
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="message">异常消息</param>
    public BusinessException(string message) : base(message)
    {
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="message">异常消息</param>
    /// <param name="code">错误码</param>
    public BusinessException(string message, int code) : base(message)
    {
        Code = code;
        ResultCode = System.Enum.IsDefined(typeof(ResultCode), code) ? (ResultCode)code : ResultCode.FAIL;
    }

    /// <summary>
    /// 构造函数（按业务状态码）
    /// </summary>
    /// <param name="message">异常消息</param>
    /// <param name="resultCode">业务状态码</param>
    public BusinessException(string message, ResultCode resultCode) : base(message)
    {
        ResultCode = resultCode;
        Code = (int)resultCode;
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="message">异常消息</param>
    /// <param name="innerException">内部异常</param>
    public BusinessException(string message, Exception innerException) : base(message, innerException)
    {
    }

    public static void ThrowIf(bool isTrue, string message)
    {
        if (isTrue) throw new BusinessException(message);
    }

    public static void ThrowIf(bool isTrue, Func<string> action)
    {
        if (isTrue) throw new BusinessException(action.Invoke());
    }

    public static void ThrowIf(bool isTrue, string message, Action action)
    {
        if (isTrue)
        {
            action();
            throw new BusinessException(message);
        }
    }

    /// <summary>
    /// 条件抛出业务异常（带业务状态码）
    /// </summary>
    /// <param name="isTrue">是否触发</param>
    /// <param name="message">异常消息</param>
    /// <param name="resultCode">业务状态码</param>
    public static void ThrowIf(bool isTrue, string message, ResultCode resultCode)
    {
        if (isTrue) throw new BusinessException(message, resultCode);
    }
}
