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

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

namespace FnbEngine.API.Application.Queries;

/// <summary>
/// EN: Handler for getting tables by shop.
/// VI: Handler lấy danh sách bàn theo shop.
/// </summary>
public class GetTablesQueryHandler : IRequestHandler<GetTablesQuery, IEnumerable<TableDto>>
{
    private readonly ITableRepository _tableRepository;

    public GetTablesQueryHandler(ITableRepository tableRepository)
    {
        _tableRepository = tableRepository ?? throw new ArgumentNullException(nameof(tableRepository));
    }

    public async Task<IEnumerable<TableDto>> Handle(GetTablesQuery request, CancellationToken cancellationToken)
    {
        var tables = await _tableRepository.GetByShopAsync(request.ShopId, cancellationToken);

        var allStatuses = Enumeration.GetAll<TableStatus>()
            .ToDictionary(s => s.Id, s => s.Name.ToLowerInvariant());

        return tables.Select(t => new TableDto(
            t.Id,
            t.ShopId,
            t.TableNumber,
            t.Capacity,
            t.Zone,
            allStatuses.TryGetValue(t.StatusId, out var name) ? name : "available",
            t.HourlyRate,
            t.PositionX,
            t.PositionY,
            t.QrToken
        ));
    }
}
