using MediatR;
using MiningService.Domain.AggregatesModel.CircleAggregate;
using MiningService.Domain.Exceptions;

namespace MiningService.API.Application.Commands;

/// <summary>
/// EN: Command to accept circle invitation.
/// VI: Command để chấp nhận lời mời vòng tròn.
/// </summary>
public record AcceptCircleInviteCommand(Guid UserId, Guid InviteId) : IRequest<AcceptCircleInviteResult>;

public record AcceptCircleInviteResult(bool Success, string Message);

public class AcceptCircleInviteCommandHandler : IRequestHandler<AcceptCircleInviteCommand, AcceptCircleInviteResult>
{
    private readonly ICircleRepository _circleRepository;

    public AcceptCircleInviteCommandHandler(ICircleRepository circleRepository)
    {
        _circleRepository = circleRepository;
    }

    public async Task<AcceptCircleInviteResult> Handle(AcceptCircleInviteCommand request, CancellationToken cancellationToken)
    {
        // Note: In a real implementation, we'd have an Invite entity
        // For now, this is a simplified version
        var circle = await _circleRepository.GetByIdAsync(request.InviteId, cancellationToken);
        if (circle == null)
            throw new CircleDomainException($"Circle not found: {request.InviteId}");

        // Add member to circle
        circle.AddMember(request.UserId);
        await _circleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return new AcceptCircleInviteResult(true, "Successfully joined circle");
    }
}

/// <summary>
/// EN: Command to remove a member from circle.
/// VI: Command để xóa thành viên khỏi vòng tròn.
/// </summary>
public record RemoveCircleMemberCommand(Guid OwnerId, Guid MemberId) : IRequest<RemoveCircleMemberResult>;

public record RemoveCircleMemberResult(bool Success, string Message);

public class RemoveCircleMemberCommandHandler : IRequestHandler<RemoveCircleMemberCommand, RemoveCircleMemberResult>
{
    private readonly ICircleRepository _circleRepository;

    public RemoveCircleMemberCommandHandler(ICircleRepository circleRepository)
    {
        _circleRepository = circleRepository;
    }

    public async Task<RemoveCircleMemberResult> Handle(RemoveCircleMemberCommand request, CancellationToken cancellationToken)
    {
        var circle = await _circleRepository.GetByOwnerIdAsync(request.OwnerId, cancellationToken);
        if (circle == null)
            throw new CircleDomainException("Circle not found");

        circle.RemoveMember(request.MemberId);
        await _circleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return new RemoveCircleMemberResult(true, "Member removed successfully");
    }
}
