📄 StackExchangeSearchProvider.cs
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Extensions.Options;
using MSearch.Domain;

namespace MSearch.SearchProviders.StackExchange;

internal sealed class StackExchangeSearchProvider(IOptions<StackExchangeOptions> options, HttpClient httpClient)
    : ISearchProvider
{
    private readonly string apiKey = options.Value.ApiKey;
    private readonly string site = options.Value.Site;

    public async IAsyncEnumerable<SearchResult> Search(
        SearchQuery query,
        [EnumeratorCancellation] CancellationToken cancellationToken
    )
    {
        var response = await httpClient.GetFromJsonAsync(
            $"search/advanced?order=desc&sort=relevance&pagesize=10&site={site}&q={Uri.EscapeDataString(query.Term)}&key={apiKey}",
            StackExchangeJsonSerializerContext.Default.StackExchangeResponse,
            cancellationToken
        );
        if (response is null)
        {
            yield break;
        }
        foreach (var item in response.Items)
        {
            yield return Map(item);
        }
    }

    private static SearchResult Map(StackExchangeItem item) => new(item.Title, Summary: null, new(item.Link));
}