using Hotline.Caching.Interfaces;
using Hotline.Realtimes;
using XF.Domain.Cache;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;

namespace Hotline.Caching.Services;

public class RealtimeCacheManager : IRealtimeCacheManager, IScopeDependency
{
    private readonly ITypedCache<RealtimeConnection> _cacheConnection;

    public RealtimeCacheManager(ITypedCache<RealtimeConnection> cacheConnection)
    {
        _cacheConnection = cacheConnection;
    }

    public async Task<RealtimeConnection> GetConnectionAsync(string userId, CancellationToken cancellationToken)
    {
        var connection = await _cacheConnection.GetAsync(userId, cancellationToken);
        if (connection is null)
            throw new UserFriendlyException($"未建立实时服务连接, userId: {userId}", "未建立实时服务连接");
        return connection;
    }

    public async Task<bool> IsInGroupAsync(string useId, string groupName, CancellationToken cancellationToken)
    {
        var connection = await GetConnectionAsync(useId, cancellationToken);
        return connection.IsInGroup(groupName);
    }

    public async Task<RealtimeConnection> GetConnectionOtherAsync(string userId, CancellationToken cancellationToken)
    {
        return await _cacheConnection.GetAsync(userId, cancellationToken);
    }
}