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

namespace MiningService.API.Application.Queries;

/// <summary>
/// EN: Query to get circle details.
/// VI: Query để lấy chi tiết vòng tròn.
/// </summary>
public record GetCircleQuery(Guid UserId) : IRequest<CircleDto?>;

public record CircleDto(
    Guid CircleId,
    string Name,
    Guid OwnerId,
    int MemberCount,
    decimal TrustScore,
    decimal BonusMultiplier,
    bool IsValid,
    string Status,
    List<CircleMemberDto> Members);

public record CircleMemberDto(
    Guid MinerId,
    DateTime JoinedAt,
    bool IsActive);

public class GetCircleQueryHandler : IRequestHandler<GetCircleQuery, CircleDto?>
{
    private readonly ICircleRepository _circleRepository;
    private readonly IMinerRepository _minerRepository;

    public GetCircleQueryHandler(
        ICircleRepository circleRepository,
        IMinerRepository minerRepository)
    {
        _circleRepository = circleRepository;
        _minerRepository = minerRepository;
    }

    public async Task<CircleDto?> Handle(GetCircleQuery request, CancellationToken cancellationToken)
    {
        var miner = await _minerRepository.GetByUserIdAsync(request.UserId, cancellationToken);
        if (miner == null || !miner.CircleId.HasValue) return null;

        var circle = await _circleRepository.GetByIdAsync(miner.CircleId.Value, cancellationToken);
        if (circle == null) return null;

        return new CircleDto(
            circle.Id,
            circle.Name,
            circle.OwnerId,
            circle.ActiveMemberCount,
            circle.TrustScore,
            circle.BonusMultiplier,
            circle.IsValid,
            circle.Status.ToString(),
            circle.Members.Select(m => new CircleMemberDto(
                m.MinerId,
                m.JoinedAt,
                m.IsActive
            )).ToList());
    }
}
