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

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

namespace FnbEngine.API.Application.Commands;

/// <summary>
/// EN: Handler for marking a drink as delivered.
/// VI: Handler de danh dau do uong da giao.
/// </summary>
public class MarkDrinkDeliveredCommandHandler : IRequestHandler<MarkDrinkDeliveredCommand, bool>
{
    private readonly IBaristaQueueRepository _repository;
    private readonly ILogger<MarkDrinkDeliveredCommandHandler> _logger;

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

    public async Task<bool> Handle(MarkDrinkDeliveredCommand 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.MarkDelivered();
        _repository.Update(item);
        await _repository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

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

        return true;
    }
}
