using System;
using NodePipeline.Abstractions.Interfaces;
using NodePipeline.Abstractions.Interfaces.Nodes;
using NodePipeline.Abstractions.Models.Validation;

namespace NodePipeline.Abstractions.Validators;

public sealed class StringLengthValidator(IPipelineLocalizationProvider localizer, int? min, int? max)
    : NodeFieldValidatorBase<string>(localizer)
{
    private readonly int? _max = min.HasValue && max.HasValue
        ? Math.Max(min.Value, max.Value)
        : max;

    private readonly int? _min = min.HasValue && max.HasValue
        ? Math.Min(min.Value, max.Value)
        : min;

    public override NodeFieldValidationResult Validate(INodeField<string> nodeField)
    {
        var stringLength = nodeField.Value.Length;
        if (_min.HasValue && _max.HasValue)
            if (stringLength < _min.Value || stringLength > _max.Value)
                return new NodeFieldValidationResult(ValidationResult.HasErrors,
                    Localizer.GetLocalizedString("StringLengthRangeError", Culture, _min, _max));

        if (stringLength < _min)
            return new NodeFieldValidationResult(ValidationResult.HasErrors,
                Localizer.GetLocalizedString("StringLengthMinError", Culture, _min));
        if (stringLength > _max)
            return new NodeFieldValidationResult(ValidationResult.HasErrors,
                Localizer.GetLocalizedString("StringLengthMaxError", Culture, _max));

        return SuccessResult;
    }
}