namespace CMSMicroservice.Application.InventoryItemCQ.Queries.GetLowStockItems;

public class GetLowStockItemsQueryHandler : IRequestHandler<GetLowStockItemsQuery, GetLowStockItemsResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetLowStockItemsResponseDto> Handle(GetLowStockItemsQuery request, CancellationToken cancellationToken)
    {
        var query = _context.InventoryItems
            .AsNoTracking()
            .Include(i => i.Warehouse)
            .Include(i => i.Product)
            .Include(i => i.DiscountProduct)
            .Where(i => i.Quantity <= i.LowStockThreshold);

        if (request.WarehouseId.HasValue)
        {
            query = query.Where(i => i.WarehouseId == request.WarehouseId.Value);
        }

        var totalCount = await query.CountAsync(cancellationToken);

        var items = await query
            .OrderBy(i => i.Quantity - i.ReservedQuantity)
            .Take(request.Count)
            .Select(i => new LowStockItemDto
            {
                Id = i.Id,
                ProductId = i.ProductId,
                DiscountProductId = i.DiscountProductId,
                ProductType = i.ProductType,
                WarehouseId = i.WarehouseId,
                WarehouseName = i.Warehouse != null ? i.Warehouse.Name : null,
                ProductTitle = i.Product != null ? i.Product.Title : (i.DiscountProduct != null ? i.DiscountProduct.Title : null),
                Quantity = i.Quantity,
                ReservedQuantity = i.ReservedQuantity,
                AvailableQuantity = i.Quantity - i.ReservedQuantity,
                LowStockThreshold = i.LowStockThreshold
            })
            .ToListAsync(cancellationToken);

        return new GetLowStockItemsResponseDto
        {
            Items = items,
            TotalCount = totalCount
        };
    }
}
