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

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 查询证照列表。
/// </summary>
public sealed class GetMerchantDocumentsQueryHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetMerchantDocumentsQuery, IReadOnlyList<MerchantDocumentDto>>
{
    /// <summary>
    /// 查询商户证照列表。
    /// </summary>
    /// <param name="request">查询请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>证照 DTO 列表。</returns>
    public async Task<IReadOnlyList<MerchantDocumentDto>> Handle(GetMerchantDocumentsQuery request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文并校验商户存在
        var tenantId = tenantProvider.GetCurrentTenantId();
        _ = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");

        // 2. 查询证照列表
        var documents = await merchantRepository.GetDocumentsAsync(request.MerchantId, tenantId, cancellationToken);
        return MerchantMapping.ToDocumentDtos(documents);
    }
}
