namespace CMSMicroservice.Application.InventoryItemCQ.Queries.GetInventoryItem;

public class GetInventoryItemQueryHandler : IRequestHandler<GetInventoryItemQuery, GetInventoryItemResponseDto?>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetInventoryItemResponseDto?> Handle(GetInventoryItemQuery request, CancellationToken cancellationToken)
    {
        var item = await _context.InventoryItems
            .AsNoTracking()
            .Include(i => i.Warehouse)
            .Include(i => i.Product)
            .Include(i => i.DiscountProduct)
            .Where(i => i.Id == request.Id)
            .Select(i => new GetInventoryItemResponseDto
            {
                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),
                ProductPrice = i.Product != null ? i.Product.Price : (i.DiscountProduct != null ? i.DiscountProduct.Price : 0),
                Quantity = i.Quantity,
                ReservedQuantity = i.ReservedQuantity,
                AvailableQuantity = i.AvailableQuantity,
                LowStockThreshold = i.LowStockThreshold,
                MaxStockLevel = i.MaxStockLevel,
                LastRestockedAt = i.LastRestockedAt,
                LastSoldAt = i.LastSoldAt,
                Created = i.Created
            })
            .FirstOrDefaultAsync(cancellationToken);

        return item;
    }
}
