using MediatR;
using IamService.Domain.AggregatesModel.GroupAggregate;
using IamService.Domain.Exceptions;

namespace IamService.API.Application.Commands.Groups;

/// <summary>
/// EN: Handler for RemoveGroupMemberCommand.
/// VI: Handler cho RemoveGroupMemberCommand.
/// </summary>
public class RemoveGroupMemberCommandHandler : IRequestHandler<RemoveGroupMemberCommand, bool>
{
    private readonly IGroupRepository _groupRepository;
    private readonly ILogger<RemoveGroupMemberCommandHandler> _logger;

    public RemoveGroupMemberCommandHandler(
        IGroupRepository groupRepository,
        ILogger<RemoveGroupMemberCommandHandler> logger)
    {
        _groupRepository = groupRepository;
        _logger = logger;
    }

    public async Task<bool> Handle(RemoveGroupMemberCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Removing user {UserId} from group {GroupId}", 
            request.UserId, request.GroupId);

        var group = await _groupRepository.GetByIdWithMembersAsync(request.GroupId, cancellationToken);

        if (group == null)
        {
            throw new DomainException($"Group with ID '{request.GroupId}' not found.");
        }

        group.RemoveMember(request.UserId);

        _groupRepository.Update(group);

        await _groupRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("User {UserId} removed from group {GroupId}", request.UserId, request.GroupId);

        return true;
    }
}
