using FluentValidation;

namespace TakeoutSaaS.Application.Dictionary.Validators;

/// <summary>
/// 多语言值校验器。
/// </summary>
public sealed class I18nValueValidator : AbstractValidator<Dictionary<string, string>>
{
    public I18nValueValidator()
    {
        RuleFor(x => x)
            .NotNull()
            .Must(HasAtLeastOneValue)
            .WithMessage("至少需要提供一种语言的值。");

        RuleForEach(x => x.Keys)
            .NotEmpty()
            .Matches("^[a-zA-Z]{2,5}(-[a-zA-Z]{2,5})?$")
            .WithMessage("语言代码格式不正确。");
    }

    private static bool HasAtLeastOneValue(Dictionary<string, string>? values)
    {
        if (values == null || values.Count == 0)
        {
            return false;
        }

        return values.Any(pair => !string.IsNullOrWhiteSpace(pair.Value));
    }
}
