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

namespace JSMR.Application.Tags.Queries.Search;

public sealed class SearchTagsHandler(ITagSearchProvider searchProvider, ILogger<SearchTagsHandler> logger)
{
    public async Task<SearchTagsResponse> HandleAsync(SearchTagsRequest request, CancellationToken cancellationToken)
    {
        SearchOptions<TagSearchCriteria, TagSortField> searchOptions = request.Options;
        Stopwatch stopWatch = Stopwatch.StartNew();

        SearchResult<TagSearchItem> 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 SearchTagsResponse(results);
    }
}