using FluentValidation;
using TakeoutSaaS.Application.Identity.Commands;

namespace TakeoutSaaS.Application.Identity.Validators;

/// <summary>
/// 更新用户命令验证器。
/// </summary>
public sealed class UpdateIdentityUserCommandValidator : AbstractValidator<UpdateIdentityUserCommand>
{
    /// <summary>
    /// 初始化验证规则。
    /// </summary>
    public UpdateIdentityUserCommandValidator()
    {
        RuleFor(x => x.UserId).GreaterThan(0);
        RuleFor(x => x.DisplayName).NotEmpty().MaximumLength(64);
        RuleFor(x => x.Avatar).MaximumLength(512);
        RuleFor(x => x.RowVersion).NotEmpty();
        RuleForEach(x => x.RoleIds)
            .Must(value => long.TryParse(value, out _))
            .WithMessage("角色 ID 必须为有效的数字字符串")
            .When(x => x.RoleIds != null);
        When(x => !string.IsNullOrWhiteSpace(x.Phone), () =>
        {
            RuleFor(x => x.Phone!)
                .Matches("^1[3-9]\\d{9}$")
                .WithMessage("手机号格式不正确");
        });
        When(x => !string.IsNullOrWhiteSpace(x.Email), () =>
        {
            RuleFor(x => x.Email!)
                .EmailAddress()
                .WithMessage("邮箱格式不正确");
        });
    }
}
