using JSMR.Application.Common.Search;
using JSMR.Application.Creators.Queries.Search;
using JSMR.Application.Logging;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace JSMR.Application.Circles.Queries.Search;

public sealed class SearchCirclesHandler(ICircleSearchProvider searchProvider, ILogger<SearchCreatorsHandler> logger)
{
    public async Task<SearchCirclesResponse> HandleAsync(SearchCirclesRequest request, CancellationToken cancellationToken)
    {
        SearchOptions<CircleSearchCriteria, CircleSortField> searchOptions = request.Options;

        Stopwatch stopWatch = Stopwatch.StartNew();
        LogEvents.SearchStart(logger, searchOptions.PageNumber, searchOptions.PageSize, searchOptions.Criteria);

        SearchResult<CircleSearchItem> results = await searchProvider.SearchAsync(searchOptions, cancellationToken);
        long elapsedMilliseconds = stopWatch.ElapsedMilliseconds;

        LogEvents.SearchCompleted(
            logger,
            Elapsed: elapsedMilliseconds,
            Items: results.Items.Length,
            Total: results.TotalItems,
            Page: searchOptions.PageNumber,
            Size: searchOptions.PageSize,
            Sort: searchOptions.SortOptions.ToLogObject(),
            Criteria: searchOptions.Criteria.ToLogObject()
        );

        return new SearchCirclesResponse(results);
    }
}