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 FreezeTenantCommandHandler(
    ITenantRepository tenantRepository,
    ICurrentUserAccessor currentUserAccessor)
    : IRequestHandler<FreezeTenantCommand, TenantDto>
{
    /// <inheritdoc />
    public async Task<TenantDto> Handle(FreezeTenantCommand 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.Closed)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "已注销租户不可冻结");
        }

        if (tenant.Status == TenantStatus.Suspended)
        {
            throw new BusinessException(ErrorCodes.Conflict, "租户已被冻结");
        }

        // 2. 更新租户状态
        tenant.Status = TenantStatus.Suspended;
        tenant.SuspendedAt = DateTime.UtcNow;
        tenant.SuspensionReason = request.Reason;

        // 3. (空行后) 同步暂停订阅
        if (subscription != null)
        {
            subscription.Status = SubscriptionStatus.Suspended;
            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);
    }
}

