import { Injectable } from '@nestjs/common';
import { RedisService } from './redis.service';

@Injectable()
export class PresenceRedisRepository {
  private readonly ONLINE_USERS_KEY = 'presence:online_users';

  constructor(private readonly redisService: RedisService) {}

  async updateUserPresence(userId: string, timestamp: number): Promise<void> {
    await this.redisService.zadd(this.ONLINE_USERS_KEY, timestamp, userId);
  }

  async countOnlineUsers(thresholdTimestamp: number): Promise<number> {
    return this.redisService.zcount(this.ONLINE_USERS_KEY, thresholdTimestamp, '+inf');
  }

  async getOnlineUsers(thresholdTimestamp: number, limit?: number): Promise<string[]> {
    if (limit) {
      return this.redisService.zrangebyscore(this.ONLINE_USERS_KEY, thresholdTimestamp, '+inf', 'LIMIT', 0, limit);
    }
    return this.redisService.zrangebyscore(this.ONLINE_USERS_KEY, thresholdTimestamp, '+inf');
  }

  async removeExpiredUsers(thresholdTimestamp: number): Promise<number> {
    return this.redisService.zremrangebyscore(this.ONLINE_USERS_KEY, '-inf', thresholdTimestamp);
  }

  async getUserLastHeartbeat(userId: string): Promise<number | null> {
    const score = await this.redisService.zscore(this.ONLINE_USERS_KEY, userId);
    return score ? Number(score) : null;
  }
}
