using MediatR;
using Microsoft.Extensions.Logging;
using SocialService.Domain.AggregatesModel.UserBlockAggregate;

namespace SocialService.API.Application.Commands;

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

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

    public async Task<bool> Handle(AdminDeleteBlockCommand request, CancellationToken cancellationToken)
    {
        var block = await _userBlockRepository.GetByIdAsync(request.BlockId);
        
        if (block == null)
        {
            _logger.LogWarning("Admin tried to delete non-existent block {BlockId}", request.BlockId);
            return false;
        }

        _userBlockRepository.Remove(block);
        await _userBlockRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
        
        _logger.LogInformation(
            "Admin deleted block {BlockId} from {BlockerId} to {BlockedId}",
            request.BlockId, block.BlockerId, block.BlockedId);
        
        return true;
    }
}
