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;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 租户入住进度查询处理器。
/// </summary>
public sealed class GetTenantProgressQueryHandler(
    ITenantRepository tenantRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetTenantProgressQuery, TenantProgressDto>
{
    /// <inheritdoc />
    public async Task<TenantProgressDto> Handle(GetTenantProgressQuery request, CancellationToken cancellationToken)
    {
        // 1. 校验租户上下文（租户端禁止跨租户）
        var currentTenantId = tenantProvider.GetCurrentTenantId();
        if (currentTenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "缺少租户标识");
        }

        // 2. (空行后) 兼容旧调用：若传入 TenantId，则必须与当前租户一致
        if (request.TenantId > 0 && request.TenantId != currentTenantId)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "无权查询其他租户进度");
        }

        // 3. (空行后) 查询租户
        var tenant = await tenantRepository.FindByIdAsync(currentTenantId, cancellationToken)
                     ?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");

        // 4. (空行后) 查询订阅与实名
        var subscription = await tenantRepository.GetActiveSubscriptionAsync(currentTenantId, cancellationToken);
        var verification = await tenantRepository.GetVerificationProfileAsync(currentTenantId, cancellationToken);

        // 5. (空行后) 组装进度信息
        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
        };
    }
}
