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

using MediatR;
using FnbEngine.Domain.AggregatesModel.KitchenAggregate;

namespace FnbEngine.API.Application.Commands;

public class CreateKitchenTicketCommandHandler : IRequestHandler<CreateKitchenTicketCommand, Guid>
{
    private readonly IKitchenTicketRepository _repository;

    public CreateKitchenTicketCommandHandler(IKitchenTicketRepository repository)
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
    }

    public async Task<Guid> Handle(CreateKitchenTicketCommand request, CancellationToken cancellationToken)
    {
        var ticket = new KitchenTicket(
            request.SessionId,
            request.OrderItemId,
            request.ProductId ?? request.OrderItemId,
            request.ItemName,
            request.Quantity,
            request.Station,
            request.Priority);

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

        return ticket.Id;
    }
}
