using Nalu.Web.Enrichers;
using Nalu.Web.Models;

namespace Nalu.Web.Services;

public class EnrichmentService
{
    private readonly Dictionary<string, IEnricher> _enrichers;

    public EnrichmentService(IEnumerable<IEnricher> enrichers)
    {
        _enrichers = enrichers.ToDictionary(e => e.Name, StringComparer.OrdinalIgnoreCase);
    }

    public async Task<EnrichmentResult> EnrichAsync(ValidatorDefinition validator, string? value, CancellationToken ct)
    {
        if (value is null || validator.Enrichers.Count == 0)
            return EnrichmentResult.Ok(value);

        foreach (var name in validator.Enrichers)
        {
            if (value is null) break;
            if (!_enrichers.TryGetValue(name, out var enricher)) continue;

            var result = await enricher.EnrichAsync(value, ct);
            if (result.WasInvalidated) return EnrichmentResult.NotFound();
            value = result.Value;
        }

        return EnrichmentResult.Ok(value);
    }
}
