using Nalu.Web.PostProcessors;

namespace Nalu.Web.Services;

public record PostProcessorOutput
{
    public string? Value { get; init; }
    public bool IsValid { get; init; } = true;
    public bool WasCorrected { get; init; }
    public string? OriginalValue { get; init; }
    public string? InvalidReason { get; init; }
    /// Overrides suggestion template key — set by processors like CalculateAge ("when_minor").
    public string? SuggestionKeyOverride { get; init; }
}

public class PostProcessorRegistry
{
    private readonly Dictionary<string, IPostProcessor> _processors;

    public PostProcessorRegistry(IEnumerable<IPostProcessor> processors)
    {
        _processors = processors.ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase);
    }

    public PostProcessorOutput Apply(IReadOnlyList<string> processorNames, string? value)
    {
        bool wasCorrected = false;
        string? originalValue = null;
        string? suggestionKeyOverride = null;

        foreach (var name in processorNames)
        {
            if (!_processors.TryGetValue(name, out var processor)) continue;

            var result = processor.Process(value);

            if (!result.IsValid)
                return new PostProcessorOutput { Value = null, IsValid = false, InvalidReason = result.InvalidReason };

            if (result.WasCorrected)
            {
                wasCorrected = true;
                originalValue ??= result.OriginalValue;
            }

            if (result.SuggestionKeyOverride is not null)
                suggestionKeyOverride = result.SuggestionKeyOverride;

            value = result.Value;
        }

        return new PostProcessorOutput
        {
            Value = value,
            IsValid = true,
            WasCorrected = wasCorrected,
            OriginalValue = originalValue,
            SuggestionKeyOverride = suggestionKeyOverride
        };
    }
}
