using MediatR;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.App.Tenants.Queries;
using TakeoutSaaS.Domain.Tenants.Enums;
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 GetTenantProgressQueryHandler(ITenantRepository tenantRepository)
    : IRequestHandler<GetTenantProgressQuery, TenantProgressDto>
{
    /// <inheritdoc />
    public async Task<TenantProgressDto> Handle(GetTenantProgressQuery 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 TenantProgressDto
        {
            TenantId = tenant.Id,
            Code = tenant.Code,
            Status = tenant.Status,
            VerificationStatus = verification?.Status ?? TenantVerificationStatus.Draft,
            EffectiveFrom = subscription?.EffectiveFrom ?? tenant.EffectiveFrom,
            EffectiveTo = subscription?.EffectiveTo ?? tenant.EffectiveTo
        };
    }
}
