using System.Linq;
using MediatR;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Application.App.Stores.Queries;
using TakeoutSaaS.Domain.Stores.Repositories;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 桌台区域列表查询处理器。
/// </summary>
public sealed class ListStoreTableAreasQueryHandler(IStoreRepository storeRepository)
    : IRequestHandler<ListStoreTableAreasQuery, IReadOnlyList<StoreTableAreaDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<StoreTableAreaDto>> Handle(ListStoreTableAreasQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询门店并解析租户
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId: null, cancellationToken);
        if (store is null)
        {
            return [];
        }
        var tenantId = store.TenantId;

        // 2. (空行后) 查询区域列表
        var areas = await storeRepository.GetTableAreasAsync(request.StoreId, tenantId, cancellationToken);

        // 3. (空行后) 映射 DTO
        return areas.Select(StoreMapping.ToDto).ToList();
    }
}
