namespace CMSMicroservice.Application.UserPackagePurchaseCQ.Queries.GetAllUserPackagePurchaseByFilter;

public class GetAllUserPackagePurchaseByFilterQueryHandler
    : IRequestHandler<GetAllUserPackagePurchaseByFilterQuery, GetAllUserPackagePurchaseByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllUserPackagePurchaseByFilterResponseDto> Handle(
        GetAllUserPackagePurchaseByFilterQuery request,
        CancellationToken cancellationToken)
    {
        var query = _context.UserPackagePurchases
            .Include(x => x.User)
            .Include(x => x.Package)
            .AsNoTracking()
            .ApplyUserPackagePurchaseFilter(request.Filter)
            .ApplyOrder(sortBy: request.SortBy ?? "-PurchasedAt");

        return new GetAllUserPackagePurchaseByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query
                .PaginatedListAsync(paginationState: request.PaginationState)
                .Select(x => new GetAllUserPackagePurchaseByFilterResponseModel
                {
                    Id = x.Id,
                    UserId = x.UserId,
                    UserName = x.User != null ? $"{x.User.FirstName} {x.User.LastName}" : string.Empty,
                    UserMobile = x.User != null ? x.User.Mobile : string.Empty,
                    PackageId = x.PackageId,
                    PackageName = x.Package != null ? x.Package.Title : string.Empty,
                    PurchaseMethod = x.PurchaseMethod,
                    PurchasedAt = x.PurchasedAt,
                    Amount = x.Amount,
                    OrderId = x.OrderId,
                    TransactionId = x.TransactionId,
                    Created = x.Created
                })
                .ToListAsync(cancellationToken)
        };
    }
}
