using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 解冻租户处理器。
/// </summary>
public sealed class UnfreezeTenantCommandHandler(
    ITenantRepository tenantRepository,
    ICurrentUserAccessor currentUserAccessor)
    : IRequestHandler<UnfreezeTenantCommand, TenantDto>
{
    /// <inheritdoc />
    public async Task<TenantDto> Handle(UnfreezeTenantCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户与订阅
        var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");

        var subscription = await tenantRepository.GetActiveSubscriptionAsync(request.TenantId, cancellationToken);
        var verification = await tenantRepository.GetVerificationProfileAsync(request.TenantId, cancellationToken);

        var previousStatus = tenant.Status;
        if (tenant.Status != TenantStatus.Suspended)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "当前租户未处于冻结状态");
        }

        // 2. 计算恢复状态（到期则回到到期状态）
        var now = DateTime.UtcNow;
        var isExpired = subscription != null && subscription.EffectiveTo <= now;

        tenant.Status = isExpired ? TenantStatus.Expired : TenantStatus.Active;
        tenant.SuspendedAt = null;
        tenant.SuspensionReason = null;

        // 3. (空行后) 同步订阅状态
        if (subscription != null)
        {
            subscription.Status = isExpired ? SubscriptionStatus.GracePeriod : SubscriptionStatus.Active;
            await tenantRepository.UpdateSubscriptionAsync(subscription, cancellationToken);
        }

        await tenantRepository.UpdateTenantAsync(tenant, cancellationToken);

        // 4. (空行后) 记录审计
        var actorName = currentUserAccessor.IsAuthenticated
            ? $"user:{currentUserAccessor.UserId}"
            : "system";

        await tenantRepository.AddAuditLogAsync(new TenantAuditLog
        {
            TenantId = tenant.Id,
            Action = TenantAuditAction.StatusChanged,
            Title = "解冻租户",
            Description = request.Reason,
            OperatorId = currentUserAccessor.UserId == 0 ? null : currentUserAccessor.UserId,
            OperatorName = actorName,
            PreviousStatus = previousStatus,
            CurrentStatus = tenant.Status
        }, cancellationToken);

        // 5. 保存并返回
        await tenantRepository.SaveChangesAsync(cancellationToken);
        return TenantMapping.ToDto(tenant, subscription, verification);
    }
}

