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 GetMerchantDetailQueryHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetMerchantDetailQuery, MerchantDetailDto>
{
    /// <summary>
    /// 查询商户详情，包括证照和合同。
    /// </summary>
    /// <param name="request">查询请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>商户详情 DTO。</returns>
    public async Task<MerchantDetailDto> Handle(GetMerchantDetailQuery request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文并查询商户
        var tenantId = tenantProvider.GetCurrentTenantId();
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
                       ?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");

        // 2. 查询证照与合同
        var documents = await merchantRepository.GetDocumentsAsync(request.MerchantId, tenantId, cancellationToken);
        var contracts = await merchantRepository.GetContractsAsync(request.MerchantId, tenantId, cancellationToken);

        // 3. 返回明细 DTO
        return new MerchantDetailDto
        {
            Merchant = MerchantMapping.ToDto(merchant),
            Documents = MerchantMapping.ToDocumentDtos(documents),
            Contracts = MerchantMapping.ToContractDtos(contracts)
        };
    }
}
