using MediatR;
using TakeoutSaaS.Application.App.Merchants.Queries;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 读取可选类目。
/// </summary>
public sealed class GetMerchantCategoriesQueryHandler(
    IMerchantCategoryRepository categoryRepository,
    ITenantProvider tenantProvider)
    : 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 tenantId = tenantProvider.GetCurrentTenantId();
        var categories = await categoryRepository.ListAsync(tenantId, cancellationToken);

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