namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetUserNetworkPosition;

public class GetUserNetworkPositionQueryHandler : IRequestHandler<GetUserNetworkPositionQuery, UserNetworkPositionDto?>
{
    private readonly IApplicationDbContext _context;

    public GetUserNetworkPositionQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<UserNetworkPositionDto?> Handle(GetUserNetworkPositionQuery request, CancellationToken cancellationToken)
    {
        var user = await _context.Users
            .AsNoTracking()
            .Where(x => x.Id == request.UserId)
            .Select(x => new
            {
                x.Id,
                x.Mobile,
                x.FirstName,
                x.LastName,
                x.NetworkParentId,
                x.LegPosition
            })
            .FirstOrDefaultAsync(cancellationToken);

        if (user == null)
        {
            return null;
        }

        // شمارش فرزندان
        var childrenCount = await _context.Users
            .CountAsync(x => x.NetworkParentId == request.UserId, cancellationToken);

        var leftChildCount = await _context.Users
            .CountAsync(x => x.NetworkParentId == request.UserId && x.LegPosition == NetworkLeg.Left,
                cancellationToken);

        var rightChildCount = await _context.Users
            .CountAsync(x => x.NetworkParentId == request.UserId && x.LegPosition == NetworkLeg.Right,
                cancellationToken);

        // اطلاعات والد
        string? parentMobile = null;
        if (user.NetworkParentId.HasValue)
        {
            parentMobile = await _context.Users
                .Where(x => x.Id == user.NetworkParentId)
                .Select(x => x.Mobile)
                .FirstOrDefaultAsync(cancellationToken);
        }

        return new UserNetworkPositionDto
        {
            UserId = user.Id,
            Mobile = user.Mobile,
            FirstName = user.FirstName,
            LastName = user.LastName,
            NetworkParentId = user.NetworkParentId,
            ParentMobile = parentMobile,
            LegPosition = user.LegPosition,
            TotalChildren = childrenCount,
            LeftChildCount = leftChildCount,
            RightChildCount = rightChildCount,
            IsInNetwork = user.NetworkParentId.HasValue
        };
    }
}
