using MediatR;
using TakeoutSaaS.Application.App.Merchants.Dto;
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 ListMerchantCategoriesQueryHandler(
    IMerchantCategoryRepository categoryRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ListMerchantCategoriesQuery, IReadOnlyList<MerchantCategoryDto>>
{
    /// <summary>
    /// 列出所有类目。
    /// </summary>
    /// <param name="request">查询请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>类目 DTO 列表。</returns>
    public async Task<IReadOnlyList<MerchantCategoryDto>> Handle(ListMerchantCategoriesQuery request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文
        var tenantId = tenantProvider.GetCurrentTenantId();
        var categories = await categoryRepository.ListAsync(tenantId, cancellationToken);

        // 2. 映射 DTO
        return MerchantMapping.ToCategoryDtos(categories);
    }
}
