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

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

namespace FnbEngine.API.Application.Commands;

/// <summary>
/// EN: Handler for starting drink preparation.
/// VI: Handler de bat dau pha che do uong.
/// </summary>
public class StartPreparingCommandHandler : IRequestHandler<StartPreparingCommand, bool>
{
    private readonly IBaristaQueueRepository _repository;
    private readonly ILogger<StartPreparingCommandHandler> _logger;

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

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

        _logger.LogInformation(
            "Barista {BaristaName} started preparing {DrinkName} (ID: {QueueItemId})",
            request.BaristaName, item.DrinkName, item.Id);

        return true;
    }
}
