using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetNetworkTree;

namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetMyNetworkTree;

/// <summary>
/// Handler برای دریافت درخت شبکه کاربر جاری
/// </summary>
public class GetMyNetworkTreeQueryHandler : IRequestHandler<GetMyNetworkTreeQuery, NetworkTreeDto?>
{
    private readonly ICurrentUserService _currentUser;
    private readonly ISender _sender;

    public GetMyNetworkTreeQueryHandler(
        ICurrentUserService currentUser,
        ISender sender)
    {
        _currentUser = currentUser;
        _sender = sender;
    }

    public async Task<NetworkTreeDto?> Handle(GetMyNetworkTreeQuery request, CancellationToken cancellationToken)
    {
        // دریافت UserId از JWT
        var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
        if (userId == 0)
        {
            throw new UnauthorizedAccessException("User not authenticated");
        }

        // استفاده از GetNetworkTreeQuery موجود با UserId از JWT
        var query = new GetNetworkTreeQuery
        {
            UserId = userId,
            MaxDepth = request.MaxDepth > 0 ? request.MaxDepth : 3
        };

        return await _sender.Send(query, cancellationToken);
    }
}
