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

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 桌码列表查询处理器。
/// </summary>
public sealed class ListStoreTablesQueryHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ListStoreTablesQuery, IReadOnlyList<StoreTableDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<StoreTableDto>> Handle(ListStoreTablesQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询桌码列表
        var tenantId = tenantProvider.GetCurrentTenantId();
        var tables = await storeRepository.GetTablesAsync(request.StoreId, tenantId, cancellationToken);

        // 2. 过滤
        if (request.AreaId.HasValue)
        {
            tables = tables.Where(x => x.AreaId == request.AreaId.Value).ToList();
        }

        if (request.Status.HasValue)
        {
            tables = tables.Where(x => x.Status == request.Status.Value).ToList();
        }

        // 3. 映射 DTO
        return tables.Select(StoreMapping.ToDto).ToList();
    }
}
