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

namespace JSMR.Application.Creators.Queries.Search;

public sealed class SearchCreatorsHandler(ICreatorSearchProvider searchProvider, ILogger<SearchCreatorsHandler> logger)
{
    public async Task<SearchCreatorsResponse> HandleAsync(SearchCreatorsRequest request, CancellationToken cancellationToken)
    {
        SearchOptions<CreatorSearchCriteria, CreatorSortField> searchOptions = request.Options;
        Stopwatch stopWatch = Stopwatch.StartNew();

        SearchResult<CreatorSearchItem> 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 SearchCreatorsResponse(results);
    }
}