using CMSMicroservice.Application.UserPackagePurchaseCQ.Queries.GetAllUserPackagePurchaseByFilter;

namespace CMSMicroservice.Application.UserPackagePurchaseCQ.Queries.GetUserPackagePurchaseSummary;

public class GetUserPackagePurchaseSummaryQueryHandler
    : IRequestHandler<GetUserPackagePurchaseSummaryQuery, GetUserPackagePurchaseSummaryResponseDto>
{
    private readonly IApplicationDbContext _context;

    public GetUserPackagePurchaseSummaryQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<GetUserPackagePurchaseSummaryResponseDto> Handle(
        GetUserPackagePurchaseSummaryQuery request,
        CancellationToken cancellationToken)
    {
        var query = _context.UserPackagePurchases
            .AsNoTracking()
            .ApplyUserPackagePurchaseFilter(request.Filter);

        var totalCount = await query.LongCountAsync(cancellationToken);
        var totalAmount = totalCount > 0 ? await query.SumAsync(x => x.Amount, cancellationToken) : 0;

        return new GetUserPackagePurchaseSummaryResponseDto
        {
            TotalCount = totalCount,
            TotalAmount = totalAmount
        };
    }
}
