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

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

namespace FnbEngine.API.Application.Commands;

public class UpdateTicketStatusCommandHandler : IRequestHandler<UpdateTicketStatusCommand, bool>
{
    private readonly IKitchenTicketRepository _repository;

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

    public async Task<bool> Handle(UpdateTicketStatusCommand request, CancellationToken cancellationToken)
    {
        var ticket = await _repository.GetByIdAsync(request.TicketId, cancellationToken);
        if (ticket == null)
        {
            throw new InvalidOperationException($"Ticket {request.TicketId} not found");
        }

        switch (request.Status.ToLowerInvariant())
        {
            case "inprogress":
                ticket.MarkAsInProgress();
                break;
            case "ready":
                ticket.MarkAsReady();
                break;
            case "served":
                ticket.MarkAsServed();
                break;
            default:
                throw new ArgumentException($"Invalid status: {request.Status}");
        }

        _repository.Update(ticket);
        await _repository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return true;
    }
}
