using System;
using System.Threading;
using System.Threading.Tasks;
using Knot.Contracts.Admin.Abstractions;
using Knot.Contracts.Auth.Application.Abstractions;
using Knot.Contracts.Auth.Domain;
using MediatR;

namespace Knot.Modules.Admin.Application.Admin.Commands;

public record UnbanUserCommand(Guid UserId) : ICommand<SuccessResponse>;

internal sealed class UnbanUserCommandHandler : ICommandHandler<UnbanUserCommand, SuccessResponse>
{
    private readonly IUserRepository _userRepository;
    private readonly IAuthUnitOfWork _unitOfWork;

    public UnbanUserCommandHandler(IUserRepository userRepository, IAuthUnitOfWork unitOfWork)
    {
        _userRepository = userRepository;
        _unitOfWork = unitOfWork;
    }

    public async Task<Result<SuccessResponse>> Handle(UnbanUserCommand request, CancellationToken cancellationToken)
    {
        var user = await _userRepository.GetByIdAsync(request.UserId, cancellationToken);
        if (user == null) return Result.Failure<SuccessResponse>(Error.NotFound("User.NotFound", "User not found"));

        user.IsBanned = false;
        user.BannedUntil = null;

        await _userRepository.UpdateAsync(user, cancellationToken);
        await _unitOfWork.SaveChangesAsync(cancellationToken);
        return Result.Success(new SuccessResponse(true));
    }
}
