using MangaReader.Core.Sources;

namespace MangaReader.Core.Search;

public class MangaSearchCoordinator(IEnumerable<IMangaSearchProvider> searchProviders) : IMangaSearchCoordinator
{
    public async Task<Dictionary<string, MangaSearchResult[]>> SearchAsync(string keyword, CancellationToken cancellationToken)
    {
        var searchTasks = searchProviders.Select(searchProvider =>
            GetMangaSearchResultsAsync(searchProvider, keyword, cancellationToken));

        var allResults = await Task.WhenAll(searchTasks);

        return allResults.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
    }

    private static async Task<KeyValuePair<string, MangaSearchResult[]>> GetMangaSearchResultsAsync(
        IMangaSearchProvider searchProvider, string keyword, CancellationToken cancellationToken)
    {
        string sourceName = searchProvider is IMangaSourceComponent sourceComponent ? sourceComponent.SourceId : "Unknown";
        MangaSearchResult[] results = await searchProvider.SearchAsync(keyword, cancellationToken);

        return new KeyValuePair<string, MangaSearchResult[]>(sourceName, results);
    }
}