using CMSMicroservice.Application.Common.Exceptions;

namespace CMSMicroservice.Application.InventoryItemCQ.Commands.DeleteInventoryItem;

public class DeleteInventoryItemCommandHandler : IRequestHandler<DeleteInventoryItemCommand, DeleteInventoryItemResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<DeleteInventoryItemResponseDto> Handle(DeleteInventoryItemCommand 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 (item.ReservedQuantity > 0)
        {
            throw new InvalidOperationException("Cannot delete inventory item with reserved quantity");
        }

        _context.InventoryItems.Remove(item);
        await _context.SaveChangesAsync(cancellationToken);

        return new DeleteInventoryItemResponseDto { Success = true };
    }
}
