import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { Injectable } from '@nestjs/common';
import { GetOnlineCountQuery } from './get-online-count.query';
import { PresenceRedisRepository } from '../../../infrastructure/redis/presence-redis.repository';
import { OnlineDetectionService } from '../../../domain/services/online-detection.service';

export interface OnlineCountResult {
  count: number;
  windowSeconds: number;
  queriedAt: Date;
}

@Injectable()
@QueryHandler(GetOnlineCountQuery)
export class GetOnlineCountHandler implements IQueryHandler<GetOnlineCountQuery> {
  constructor(
    private readonly presenceRedisRepository: PresenceRedisRepository,
    private readonly onlineDetectionService: OnlineDetectionService,
  ) {}

  async execute(query: GetOnlineCountQuery): Promise<OnlineCountResult> {
    const now = new Date();
    const threshold = this.onlineDetectionService.getOnlineThreshold(now);

    const count = await this.presenceRedisRepository.countOnlineUsers(threshold);

    return {
      count,
      windowSeconds: this.onlineDetectionService.getWindowSeconds(),
      queriedAt: now,
    };
  }
}
