namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetAllTransactionsByFilter;

public class GetAllTransactionsByFilterQueryHandler : IRequestHandler<GetAllTransactionsByFilterQuery, GetAllTransactionsByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllTransactionsByFilterResponseDto> Handle(GetAllTransactionsByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Transactions
            .AsNoTracking()
            .ApplyTransactionFilter(request.Filter)
            .ApplyOrder(sortBy: request.SortBy ?? "-Created");

        return new GetAllTransactionsByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query
                .PaginatedListAsync(paginationState: request.PaginationState)
                .Select(x => new GetAllTransactionsByFilterResponseModel
                {
                    Id = x.Id,
                    Amount = x.Amount,
                    Description = x.Description,
                    PaymentStatus = x.PaymentStatus,
                    PaymentDate = x.PaymentDate,
                    RefId = x.RefId,
                    Type = x.Type,
                    Created = x.Created
                })
                .ToListAsync(cancellationToken)
        };
    }
}
