using MediatR;
using System.Text.Json;
using TakeoutSaaS.Application.Identity.Abstractions;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Application.Identity.Events;
using TakeoutSaaS.Domain.Identity.Enums;
using TakeoutSaaS.Domain.Identity.Repositories;
using TakeoutSaaS.Shared.Abstractions.Security;

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 恢复用户处理器。
/// </summary>
public sealed class RestoreIdentityUserCommandHandler(
    IIdentityUserRepository identityUserRepository,
    ICurrentUserAccessor currentUserAccessor,
    IAdminAuthService adminAuthService,
    IIdentityOperationLogPublisher operationLogPublisher)
    : IRequestHandler<RestoreIdentityUserCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(RestoreIdentityUserCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取操作者档案（用于操作日志）
        var operatorProfile = await adminAuthService.GetProfileAsync(currentUserAccessor.UserId, cancellationToken);

        // 2. (空行后) 查询用户实体（包含已删除）
        var user = await identityUserRepository.GetForUpdateIncludingDeletedAsync(request.UserId, cancellationToken);
        if (user == null)
        {
            return false;
        }

        // 3. (空行后) 限定仅允许恢复平台管理员账号
        if (user.Portal != PortalType.Admin || user.TenantId is not null)
        {
            return false;
        }

        if (!user.DeletedAt.HasValue)
        {
            return false;
        }

        // 4. (空行后) 构建操作日志消息
        var operatorName = string.IsNullOrWhiteSpace(operatorProfile.DisplayName)
            ? operatorProfile.Account
            : operatorProfile.DisplayName;
        if (string.IsNullOrWhiteSpace(operatorName))
        {
            operatorName = $"user:{currentUserAccessor.UserId}";
        }

        var logMessage = new IdentityUserOperationLogMessage
        {
            OperationType = "identity-user:restore",
            TargetType = "identity_user",
            TargetIds = JsonSerializer.Serialize(new[] { user.Id }),
            OperatorId = currentUserAccessor.UserId.ToString(),
            OperatorName = operatorName,
            Parameters = JsonSerializer.Serialize(new { userId = user.Id, portal = PortalType.Admin.ToString() }),
            Result = JsonSerializer.Serialize(new { userId = user.Id }),
            Success = true
        };

        // 5. 恢复软删除状态并写入 Outbox
        user.DeletedAt = null;
        user.DeletedBy = null;
        await operationLogPublisher.PublishAsync(logMessage, cancellationToken);
        await identityUserRepository.SaveChangesAsync(cancellationToken);

        return true;
    }
}
