using CMSMicroservice.Application.Common.Exceptions;

namespace CMSMicroservice.Application.InventoryItemCQ.Commands.UpdateInventoryItem;

public class UpdateInventoryItemCommandHandler : IRequestHandler<UpdateInventoryItemCommand, UpdateInventoryItemResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<UpdateInventoryItemResponseDto> Handle(UpdateInventoryItemCommand request, CancellationToken cancellationToken)
    {
        var item = await _context.InventoryItems
            .FirstOrDefaultAsync(i => i.Id == request.Id, cancellationToken);

        if (item == null)
        {
            throw new NotFoundException(nameof(Domain.Entities.InventoryItem), request.Id);
        }

        if (request.MinimumStock.HasValue)
        {
            item.LowStockThreshold = request.MinimumStock.Value;
        }

        if (request.MaximumStock.HasValue)
        {
            item.MaxStockLevel = request.MaximumStock.Value;
        }

        if (request.ReorderPoint.HasValue)
        {
            item.ReorderPoint = request.ReorderPoint.Value;
        }

        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateInventoryItemResponseDto
        {
            Id = item.Id,
            ProductId = item.ProductId ?? item.DiscountProductId ?? 0,
            WarehouseId = item.WarehouseId,
            Quantity = item.Quantity,
            ReservedQuantity = item.ReservedQuantity,
            AvailableQuantity = item.AvailableQuantity,
            MinimumStock = item.LowStockThreshold,
            MaximumStock = item.MaxStockLevel,
            ReorderPoint = item.ReorderPoint
        };
    }
}
