using MangaReader.Core.HttpService;
using System.Text.Json;

namespace MangaReader.Core.Search;

public abstract class MangaSearchProviderBase<T>(IHttpService httpService) : IMangaSearchProvider
{
    public abstract string SourceId { get;}

    private static readonly JsonSerializerOptions _jsonSerializerOptions = new()
    {
        PropertyNameCaseInsensitive = true
    };

    public async Task<MangaSearchResult[]> SearchAsync(string keyword, CancellationToken cancellationToken)
    {
        T? searchResult = await GetSearchResultAsync(keyword, cancellationToken);

        if (searchResult == null)
            return [];

        return GetSearchResult(searchResult);
    }

    private async Task<T?> GetSearchResultAsync(string keyword, CancellationToken cancellationToken)
    {
        string url = GetSearchUrl(keyword);
        string response = await httpService.GetStringAsync(url, cancellationToken);

        return JsonSerializer.Deserialize<T>(response, _jsonSerializerOptions);
    }

    protected abstract string GetSearchUrl(string keyword);
    protected abstract MangaSearchResult[] GetSearchResult(T searchResult);
}