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

namespace SocialService.API.Application.Commands;

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

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

    public async Task<bool> Handle(UnfollowUserCommand request, CancellationToken cancellationToken)
    {
        var relationship = await _relationshipRepository.GetByUsersAndTypeAsync(
            request.FollowerId, 
            request.FolloweeId, 
            RelationshipType.Following);

        if (relationship == null)
        {
            throw new SocialDomainException("Not following this user");
        }

        relationship.Remove();
        _relationshipRepository.Update(relationship);
        await _relationshipRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("User {FollowerId} unfollowed {FolloweeId}",
            request.FollowerId, request.FolloweeId);

        return true;
    }
}
