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

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

namespace FnbEngine.API.Application.Commands;

/// <summary>
/// EN: Handler for adding a drink to the barista queue.
/// VI: Handler de them do uong vao hang doi barista.
/// </summary>
public class QueueDrinkCommandHandler : IRequestHandler<QueueDrinkCommand, QueueDrinkResult>
{
    private readonly IBaristaQueueRepository _repository;
    private readonly ILogger<QueueDrinkCommandHandler> _logger;

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

    public async Task<QueueDrinkResult> Handle(QueueDrinkCommand request, CancellationToken cancellationToken)
    {
        var queueItem = new BaristaQueueItem(
            request.ShopId,
            request.OrderId,
            request.OrderItemId,
            request.DrinkName,
            request.Customizations,
            request.Priority,
            request.EstimatedMinutes);

        await _repository.AddAsync(queueItem, cancellationToken);
        await _repository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation(
            "Queued drink {DrinkName} (ID: {QueueItemId}) for shop {ShopId}, order {OrderId}",
            request.DrinkName, queueItem.Id, request.ShopId, request.OrderId);

        return new QueueDrinkResult(
            queueItem.Id,
            queueItem.DrinkName,
            queueItem.Priority,
            queueItem.EstimatedMinutes,
            queueItem.StatusName);
    }
}
