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

namespace SocialService.API.Application.Commands;

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

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

    public async Task<bool> Handle(RespondToFriendRequestCommand request, CancellationToken cancellationToken)
    {
        var relationship = await _relationshipRepository.GetByIdAsync(request.RelationshipId);

        if (relationship == null)
        {
            throw new SocialDomainException("Friend request not found");
        }

        // EN: Verify the user is the addressee
        // VI: Xác minh user là người nhận yêu cầu
        if (relationship.AddresseeId != request.UserId)
        {
            throw new SocialDomainException("You can only respond to friend requests sent to you");
        }

        if (request.Accept)
        {
            relationship.Accept();
            _logger.LogInformation("Friend request {RelationshipId} accepted by {UserId}",
                request.RelationshipId, request.UserId);
        }
        else
        {
            relationship.Reject();
            _logger.LogInformation("Friend request {RelationshipId} rejected by {UserId}",
                request.RelationshipId, request.UserId);
        }

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

        return true;
    }
}
