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

namespace SocialService.API.Application.Commands;

/// <summary>
/// EN: Handler for AdminDeleteRelationshipCommand.
/// VI: Handler cho AdminDeleteRelationshipCommand.
/// </summary>
public class AdminDeleteRelationshipCommandHandler : IRequestHandler<AdminDeleteRelationshipCommand, bool>
{
    private readonly IRelationshipRepository _relationshipRepository;
    private readonly ILogger<AdminDeleteRelationshipCommandHandler> _logger;

    public AdminDeleteRelationshipCommandHandler(
        IRelationshipRepository relationshipRepository,
        ILogger<AdminDeleteRelationshipCommandHandler> logger)
    {
        _relationshipRepository = relationshipRepository;
        _logger = logger;
    }

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

        _relationshipRepository.Delete(relationship);
        await _relationshipRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
        
        _logger.LogInformation(
            "Admin deleted relationship {RelationshipId} between {RequesterId} and {AddresseeId}",
            request.RelationshipId, relationship.RequesterId, relationship.AddresseeId);
        
        return true;
    }
}
