using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Domain.Exceptions;

namespace Hotline.Tools;
public static class ObjectExtensions
{
    /// <summary>
    /// 扩展方法用于手动验证对象，并返回验证结果。
    /// </summary>
    /// <param name="obj">需要验证的对象</param>
    /// <returns>如果验证成功返回 string.Empty，否则返回错误信息</returns>
    public static string ValidateObject(this object obj, bool throwError = true)
    {
        var validationResults = new List<ValidationResult>();
        var validationContext = new ValidationContext(obj);

        // 验证对象
        bool isValid = Validator.TryValidateObject(obj, validationContext, validationResults, true);

        if (isValid)
        {
            return string.Empty;
        }
        else
        {
            var msg = string.Join("; ", validationResults.Select(result => result.ErrorMessage));
            if (throwError)
                throw UserFriendlyException.SameMessage(msg);
            // 如果验证失败，返回所有错误信息的拼接
            return msg;
        }
    }
}
