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.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;

namespace TakeoutSaaS.Application.Identity.Handlers;

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

        // 2. (空行后) 查询用户实体
        var user = await identityUserRepository.GetForUpdateAsync(request.UserId, cancellationToken);
        if (user == null)
        {
            return false;
        }

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

        // 4. 更新状态
        var previousStatus = user.Status;
        switch (request.Status)
        {
            case IdentityUserStatus.Active:
                user.Status = IdentityUserStatus.Active;
                user.LockedUntil = null;
                user.FailedLoginCount = 0;
                break;
            case IdentityUserStatus.Disabled:
                user.Status = IdentityUserStatus.Disabled;
                user.LockedUntil = null;
                break;
            case IdentityUserStatus.Locked:
                user.Status = IdentityUserStatus.Locked;
                user.LockedUntil = null;
                break;
            default:
                throw new BusinessException(ErrorCodes.BadRequest, "无效的用户状态");
        }

        // 5. 构建操作日志消息
        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:status-change",
            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(),
                previousStatus = previousStatus.ToString(),
                currentStatus = user.Status.ToString()
            }),
            Result = JsonSerializer.Serialize(new { userId = user.Id }),
            Success = true
        };

        // 6. 写入 Outbox 并保存变更
        await operationLogPublisher.PublishAsync(logMessage, cancellationToken);
        await identityUserRepository.SaveChangesAsync(cancellationToken);

        return true;
    }
}
