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

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

namespace FnbEngine.API.Application.Commands;

/// <summary>
/// EN: Handler for marking a drink as ready.
/// VI: Handler de danh dau do uong san sang.
/// </summary>
public class MarkDrinkReadyCommandHandler : IRequestHandler<MarkDrinkReadyCommand, bool>
{
    private readonly IBaristaQueueRepository _repository;
    private readonly ILogger<MarkDrinkReadyCommandHandler> _logger;

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

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

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

        return true;
    }
}
