namespace CMSMicroservice.Application.StockMovementCQ.Queries.GetStockMovementsByInventoryItem;

public class GetStockMovementsByInventoryItemQueryHandler : IRequestHandler<GetStockMovementsByInventoryItemQuery, GetStockMovementsByInventoryItemResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetStockMovementsByInventoryItemResponseDto> Handle(GetStockMovementsByInventoryItemQuery request, CancellationToken cancellationToken)
    {
        var query = _context.StockMovements
            .AsNoTracking()
            .Where(s => s.InventoryItemId == request.InventoryItemId);

        var totalCount = await query.CountAsync(cancellationToken);

        var movements = await query
            .OrderByDescending(s => s.Created)
            .Skip(request.Skip)
            .Take(request.Take)
            .Select(s => new StockMovementHistoryDto
            {
                Id = s.Id,
                MovementType = s.MovementType,
                Quantity = s.Quantity,
                QuantityBefore = s.QuantityBefore,
                QuantityAfter = s.QuantityAfter,
                Note = s.Note,
                ReferenceNumber = s.ReferenceNumber,
                OrderId = s.OrderId,
                DiscountOrderId = s.DiscountOrderId,
                PerformedByUserId = s.PerformedByUserId,
                Created = s.Created
            })
            .ToListAsync(cancellationToken);

        return new GetStockMovementsByInventoryItemResponseDto
        {
            Movements = movements,
            TotalCount = totalCount
        };
    }
}
