using MediatR;
using TakeoutSaaS.Application.App.Merchants.Dto;
using TakeoutSaaS.Application.App.Merchants.Queries;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Domain.Tenants.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,
    IStoreRepository storeRepository,
    ITenantRepository tenantRepository,
    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 currentTenantId = tenantProvider.GetCurrentTenantId();
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, currentTenantId, cancellationToken);

        if (merchant == null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
        }

        // 2. 查询门店与租户信息
        var stores = await storeRepository.GetByMerchantIdAsync(merchant.Id, merchant.TenantId, cancellationToken);
        var storeDtos = MerchantMapping.ToStoreDtos(stores);
        var tenant = await tenantRepository.FindByIdAsync(merchant.TenantId, cancellationToken);

        // 3. 返回明细 DTO
        return MerchantMapping.ToDetailDto(merchant, tenant?.Name, storeDtos);
    }
}
