using MediatR;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Application.App.Products.Queries;
using TakeoutSaaS.Domain.Products.Entities;
using TakeoutSaaS.Domain.Products.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 商品标签列表查询处理器。
/// </summary>
public sealed class GetProductLabelListQueryHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetProductLabelListQuery, IReadOnlyList<ProductLabelItemDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<ProductLabelItemDto>> Handle(GetProductLabelListQuery request, CancellationToken cancellationToken)
    {
        // 1. 读取门店标签。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var labels = await productRepository.GetLabelsByStoreAsync(tenantId, request.StoreId, cancellationToken);
        if (labels.Count == 0)
        {
            return [];
        }

        // 2. 按状态与关键字过滤。
        IEnumerable<ProductLabel> filtered = labels;
        if (!string.IsNullOrWhiteSpace(request.Status))
        {
            if (!ProductLabelMapping.TryParseStatus(request.Status, out var isEnabled))
            {
                return [];
            }

            filtered = filtered.Where(item => item.IsEnabled == isEnabled);
        }

        var normalizedKeyword = request.Keyword?.Trim().ToLowerInvariant();
        if (!string.IsNullOrWhiteSpace(normalizedKeyword))
        {
            filtered = filtered.Where(item => item.Name.ToLower().Contains(normalizedKeyword));
        }

        var filteredList = filtered
            .OrderBy(item => item.SortOrder)
            .ThenBy(item => item.Id)
            .ToList();
        if (filteredList.Count == 0)
        {
            return [];
        }

        // 3. 统计关联商品数量并映射 DTO。
        var labelIds = filteredList.Select(item => item.Id).ToList();
        var productCounts = await productRepository.CountLabelProductsByLabelIdsAsync(
            tenantId,
            request.StoreId,
            labelIds,
            cancellationToken);

        return filteredList
            .Select(label => ProductLabelDtoFactory.ToDto(label, productCounts))
            .ToList();
    }
}
