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;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 查询证照列表。
/// </summary>
public sealed class GetMerchantDocumentsQueryHandler(
    IMerchantRepository merchantRepository)
    : 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 merchant = await merchantRepository.FindByIdAsync(request.MerchantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");

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