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

using MediatR;
using FnbEngine.Domain.AggregatesModel.TableAggregate;

namespace FnbEngine.API.Application.Commands;

/// <summary>
/// EN: Handler for updating table details.
/// VI: Handler cập nhật thông tin bàn.
/// </summary>
public class UpdateTableCommandHandler : IRequestHandler<UpdateTableCommand, bool>
{
    private readonly ITableRepository _tableRepository;
    private readonly ILogger<UpdateTableCommandHandler> _logger;

    public UpdateTableCommandHandler(
        ITableRepository tableRepository,
        ILogger<UpdateTableCommandHandler> logger)
    {
        _tableRepository = tableRepository ?? throw new ArgumentNullException(nameof(tableRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<bool> Handle(UpdateTableCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Updating table {TableId}", request.TableId);

        var table = await _tableRepository.GetByIdAsync(request.TableId, cancellationToken);
        if (table == null)
            throw new InvalidOperationException($"Table not found: {request.TableId}");

        if (request.PositionX.HasValue && request.PositionY.HasValue)
            table.SetPosition(request.PositionX.Value, request.PositionY.Value);

        if (request.HourlyRate.HasValue)
            table.SetHourlyRate(request.HourlyRate.Value);

        _tableRepository.Update(table);
        await _tableRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("Updated table {TableId}", request.TableId);
        return true;
    }
}
