using MediatR;
using AdsTrackingService.Domain.AggregatesModel.ConversionAggregate;

namespace AdsTrackingService.API.Application.Queries;

/// <summary>
/// EN: Handler for GetConversionsQuery.
/// VI: Handler cho GetConversionsQuery.
/// </summary>
public class GetConversionsQueryHandler : IRequestHandler<GetConversionsQuery, IEnumerable<ConversionDto>>
{
    private readonly IConversionRepository _repository;

    public GetConversionsQueryHandler(IConversionRepository repository)
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
    }

    public async Task<IEnumerable<ConversionDto>> Handle(GetConversionsQuery request, CancellationToken ct)
    {
        IEnumerable<Conversion> conversions;

        // EN: Apply filters based on query parameters
        // VI: Áp dụng bộ lọc dựa trên tham số query
        if (request.CampaignId.HasValue)
        {
            conversions = await _repository.GetByCampaignIdAsync(
                request.CampaignId.Value, request.Skip, request.Take, ct);
        }
        else if (request.UserId.HasValue)
        {
            conversions = await _repository.GetByUserIdAsync(request.UserId.Value, ct);
            conversions = conversions.Skip(request.Skip).Take(request.Take);
        }
        else if (request.From.HasValue || request.To.HasValue)
        {
            var from = request.From ?? DateTime.MinValue;
            var to = request.To ?? DateTime.MaxValue;
            conversions = await _repository.GetByTimeRangeAsync(from, to, ct);
            conversions = conversions.Skip(request.Skip).Take(request.Take);
        }
        else
        {
            // EN: Default: get recent conversions
            // VI: Mặc định: lấy conversions gần đây
            conversions = await _repository.GetByTimeRangeAsync(
                DateTime.UtcNow.AddDays(-30), DateTime.UtcNow, ct);
            conversions = conversions.Skip(request.Skip).Take(request.Take);
        }

        return conversions.Select(c => new ConversionDto(
            c.Id,
            c.AdvertiserId,
            c.CampaignId,
            c.UserId,
            c.ConversionType,
            c.ConversionValue,
            c.Currency,
            c.ConversionTime
        ));
    }
}
