using Microsoft.Extensions.Options;
using TeleWave.Application.Common.Interfaces;

namespace TeleWave.Infrastructure.Metadata;

/// <summary>Резолвит провайдеры по ключу; доступными считает только те, у кого задан API-ключ.</summary>
public sealed class MetadataProviderResolver : IMetadataProviderResolver
{
    private readonly Dictionary<string, IMetadataProvider> _byKey;
    private readonly List<string> _available = [];

    public MetadataProviderResolver(
        IEnumerable<IMetadataProvider> providers,
        IOptions<MetadataOptions> options
    )
    {
        _byKey = providers.ToDictionary(p => p.Key, StringComparer.OrdinalIgnoreCase);
        var opt = options.Value;
        if (_byKey.ContainsKey("tmdb") && !string.IsNullOrWhiteSpace(opt.Tmdb.ApiKey))
            _available.Add("tmdb");
        if (_byKey.ContainsKey("omdb") && !string.IsNullOrWhiteSpace(opt.Omdb.ApiKey))
            _available.Add("omdb");
    }

    public IMetadataProvider? Resolve(string key) =>
        _available.Contains(key, StringComparer.OrdinalIgnoreCase)
        && _byKey.TryGetValue(key, out var provider)
            ? provider
            : null;

    public IReadOnlyList<string> AvailableKeys => _available;
}
