using System;
using System.ComponentModel.DataAnnotations;

namespace LifePayment.Domain.Shared;

/// <summary>
/// 枚举值强校验
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class EnumValidationAttribute : ValidationAttribute
{
    /// <summary>
    /// 枚举类型
    /// </summary>
    private Type _enumType;

    /// <summary>
    /// 允许空值,有值才验证,默认 false
    /// </summary>
    public bool AllowNullValue { get; set; } = false;

    public EnumValidationAttribute(Type enumType)
    {
        if (!enumType.IsEnum) throw new ArgumentException("Type must be an enum.");

        _enumType = enumType;
    }

    public string GetErrorMessage(string name) =>
    !string.IsNullOrWhiteSpace(ErrorMessage) ? FormatErrorMessage(name) : "Enum value error.";

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // 判断是否允许 空值
        if (AllowNullValue && value == null) return ValidationResult.Success;

        if (value != null && Enum.IsDefined(_enumType, value))
        {
            return ValidationResult.Success;
        }

        return new ValidationResult(GetErrorMessage(validationContext.DisplayName));
    }

}