// EN: Handler for CancelQueueItemCommand.
// VI: Handler cho CancelQueueItemCommand.

using MediatR;
using FnbEngine.Domain.AggregatesModel.BaristaAggregate;

namespace FnbEngine.API.Application.Commands;

/// <summary>
/// EN: Handler for cancelling a barista queue item.
/// VI: Handler de huy item trong hang doi barista.
/// </summary>
public class CancelQueueItemCommandHandler : IRequestHandler<CancelQueueItemCommand, bool>
{
    private readonly IBaristaQueueRepository _repository;
    private readonly ILogger<CancelQueueItemCommandHandler> _logger;

    public CancelQueueItemCommandHandler(
        IBaristaQueueRepository repository,
        ILogger<CancelQueueItemCommandHandler> logger)
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<bool> Handle(CancelQueueItemCommand request, CancellationToken cancellationToken)
    {
        var item = await _repository.GetByIdAsync(request.QueueItemId, cancellationToken);
        if (item == null)
            throw new KeyNotFoundException(
                $"Queue item {request.QueueItemId} not found / Item hang doi {request.QueueItemId} khong tim thay");

        item.Cancel();
        _repository.Update(item);
        await _repository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("Drink {DrinkName} (ID: {QueueItemId}) cancelled",
            item.DrinkName, item.Id);

        return true;
    }
}
