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

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 租户详情查询处理器。
/// </summary>
public sealed class GetTenantByIdQueryHandler(ITenantRepository tenantRepository)
    : IRequestHandler<GetTenantByIdQuery, TenantDetailDto>
{
    /// <inheritdoc />
    public async Task<TenantDetailDto> Handle(GetTenantByIdQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询租户
        var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");

        // 2. 查询订阅与认证
        var subscription = await tenantRepository.GetActiveSubscriptionAsync(request.TenantId, cancellationToken);
        var verification = await tenantRepository.GetVerificationProfileAsync(request.TenantId, cancellationToken);

        // 3. 组装返回
        return new TenantDetailDto
        {
            Tenant = TenantMapping.ToDto(tenant, subscription, verification),
            Verification = verification.ToVerificationDto(),
            Subscription = subscription.ToSubscriptionDto()
        };
    }
}
