using MediatR;
using TakeoutSaaS.Application.App.Merchants.Queries;
using TakeoutSaaS.Domain.Merchants.Repositories;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 读取可选类目。
/// </summary>
public sealed class GetMerchantCategoriesQueryHandler(
    IMerchantCategoryRepository categoryRepository)
    : IRequestHandler<GetMerchantCategoriesQuery, IReadOnlyList<string>>
{
    /// <summary>
    /// 查询启用的商户类目名称列表。
    /// </summary>
    /// <param name="request">查询请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>类目名称集合。</returns>
    public async Task<IReadOnlyList<string>> Handle(GetMerchantCategoriesQuery request, CancellationToken cancellationToken)
    {
        // 1. 读取类目列表
        var categories = await categoryRepository.ListAsync(request.TenantId, cancellationToken);

        // 2. (空行后) 过滤启用类目并去重
        return categories
            .Where(x => x.IsActive)
            .Select(x => x.Name.Trim())
            .Where(x => x.Length > 0)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToList()
            .AsReadOnly();
    }
}
