using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
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 ReviewTenantCommandHandler(
    ITenantRepository tenantRepository,
    ICurrentUserAccessor currentUserAccessor)
    : IRequestHandler<ReviewTenantCommand, TenantDto>
{
    /// <inheritdoc />
    public async Task<TenantDto> Handle(ReviewTenantCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户与认证资料
        var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");

        var verification = await tenantRepository.GetVerificationProfileAsync(request.TenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.BadRequest, "请先提交实名认证资料");

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

        // 2. 记录审核人
        var actorName = currentUserAccessor.IsAuthenticated
            ? $"user:{currentUserAccessor.UserId}"
            : "system";

        // 3. 写入审核信息
        verification.ReviewedAt = DateTime.UtcNow;
        verification.ReviewedBy = currentUserAccessor.UserId == 0 ? null : currentUserAccessor.UserId;
        verification.ReviewedByName = actorName;
        verification.ReviewRemarks = request.Reason;

        var previousStatus = tenant.Status;

        // 4. 更新租户与订阅状态
        if (request.Approve)
        {
            verification.Status = TenantVerificationStatus.Approved;
            tenant.Status = TenantStatus.Active;
            if (subscription != null)
            {
                subscription.Status = SubscriptionStatus.Active;
            }
        }
        else
        {
            verification.Status = TenantVerificationStatus.Rejected;
            tenant.Status = TenantStatus.PendingReview;
            if (subscription != null)
            {
                subscription.Status = SubscriptionStatus.Suspended;
            }
        }

        // 5. 持久化租户与认证资料
        await tenantRepository.UpdateTenantAsync(tenant, cancellationToken);
        await tenantRepository.UpsertVerificationProfileAsync(verification, cancellationToken);
        if (subscription != null)
        {
            await tenantRepository.UpdateSubscriptionAsync(subscription, cancellationToken);
        }

        // 6. 记录审核日志
        await tenantRepository.AddAuditLogAsync(new Domain.Tenants.Entities.TenantAuditLog
        {
            TenantId = tenant.Id,
            Action = request.Approve ? TenantAuditAction.VerificationApproved : TenantAuditAction.VerificationRejected,
            Title = request.Approve ? "审核通过" : "审核驳回",
            Description = request.Reason,
            OperatorId = currentUserAccessor.UserId == 0 ? null : currentUserAccessor.UserId,
            OperatorName = actorName,
            PreviousStatus = previousStatus,
            CurrentStatus = tenant.Status
        }, cancellationToken);

        // 7. 保存并返回 DTO
        await tenantRepository.SaveChangesAsync(cancellationToken);

        return TenantMapping.ToDto(tenant, subscription, verification);
    }
}
