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

namespace TakeoutSaaS.Application.Identity.Validators;

/// <summary>
/// 创建用户命令验证器。
/// </summary>
public sealed class CreateIdentityUserCommandValidator : AbstractValidator<CreateIdentityUserCommand>
{
    /// <summary>
    /// 初始化验证规则。
    /// </summary>
    public CreateIdentityUserCommandValidator()
    {
        RuleFor(x => x.Account).NotEmpty().MaximumLength(64);
        RuleFor(x => x.DisplayName).NotEmpty().MaximumLength(64);
        RuleFor(x => x.Password).NotEmpty().Length(6, 32);
        RuleFor(x => x.Avatar).MaximumLength(512);
        RuleFor(x => x.TenantId).GreaterThan(0).When(x => x.TenantId.HasValue);
        RuleForEach(x => x.RoleIds)
            .Must(value => long.TryParse(value, out _))
            .WithMessage("角色 ID 必须为有效的数字字符串");
        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("邮箱格式不正确");
        });
    }
}
