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 BanUserCommand(Guid UserId) : ICommand<SuccessResponse>;

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

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

    public async Task<Result<SuccessResponse>> Handle(BanUserCommand 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 = true;
        user.BannedUntil = null; // Permanent ban

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