using LiteCqrs;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;

namespace TeleWave.Application.Metadata.SearchShows;

public sealed class SearchShowMetadataQueryHandler(IMetadataProviderResolver resolver)
    : IQueryHandler<SearchShowMetadataQuery, Result<IReadOnlyList<MetadataCandidate>>>
{
    public async Task<Result<IReadOnlyList<MetadataCandidate>>> Handle(
        SearchShowMetadataQuery query,
        CancellationToken cancellationToken
    )
    {
        var provider = resolver.Resolve(query.Provider);
        if (provider is null)
            return Result.Failure<IReadOnlyList<MetadataCandidate>>(
                MetadataErrors.ProviderNotAvailable
            );

        if (string.IsNullOrWhiteSpace(query.Query))
            return Result.Success<IReadOnlyList<MetadataCandidate>>([]);

        try
        {
            var results = await provider.SearchShowsAsync(
                query.Query,
                query.Kind,
                cancellationToken
            );
            return Result.Success(results);
        }
        catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
        {
            // Не-2xx (например, 401 — неверный ключ) или сетевой сбой источника.
            return Result.Failure<IReadOnlyList<MetadataCandidate>>(
                MetadataErrors.ProviderRequestFailed
            );
        }
    }
}
