using MediatR;
using SocialService.Domain.AggregatesModel.UserBlockAggregate;
using SocialService.Domain.Exceptions;

namespace SocialService.API.Application.Commands;

/// <summary>
/// EN: Handler for UnblockUserCommand.
/// VI: Handler cho UnblockUserCommand.
/// </summary>
public class UnblockUserCommandHandler : IRequestHandler<UnblockUserCommand, bool>
{
    private readonly IUserBlockRepository _userBlockRepository;
    private readonly ILogger<UnblockUserCommandHandler> _logger;

    public UnblockUserCommandHandler(
        IUserBlockRepository userBlockRepository,
        ILogger<UnblockUserCommandHandler> logger)
    {
        _userBlockRepository = userBlockRepository;
        _logger = logger;
    }

    public async Task<bool> Handle(UnblockUserCommand request, CancellationToken cancellationToken)
    {
        var block = await _userBlockRepository.GetByUsersAsync(request.BlockerId, request.BlockedId);

        if (block == null)
        {
            throw new SocialDomainException("User is not blocked");
        }

        _userBlockRepository.Remove(block);
        await _userBlockRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("User {BlockerId} unblocked {BlockedId}",
            request.BlockerId, request.BlockedId);

        return true;
    }
}
