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

@Injectable()
export class WorkerHeartbeat {
  private readonly logger = new Logger(WorkerHeartbeat.name);
  private readonly KEY = 'worker:active';
  private readonly TTL = 120;

  constructor(private readonly redis: RedisService) {}

  async ping(workerName: string) {
    try {
      await this.redis.set(`${this.KEY}:${workerName}`, Date.now().toString(), this.TTL);
    } catch {}
  }

  async getActiveWorkers(): Promise<{ name: string; lastSeen: string; status: string }[]> {
    try {
      const keys = await this.redis.keys(`${this.KEY}:*`);
      const workers: { name: string; lastSeen: string; status: string }[] = [];
      for (const key of keys) {
        const timestamp = await this.redis.get(key);
        const name = key.replace(`${this.KEY}:`, '');
        const lastSeenMs = parseInt(timestamp || '0');
        const ago = Date.now() - lastSeenMs;
        const status = ago < this.TTL * 1000 ? 'online' : 'offline';
        workers.push({ name, lastSeen: new Date(lastSeenMs).toISOString(), status });
      }
      if (workers.length > 0) return workers;
    } catch (err: any) {
      this.logger.warn(`Failed to scan active workers: ${err.message}`);
    }
    return [{ name: 'zhixi-worker', lastSeen: new Date().toISOString(), status: 'unknown' }];
  }
}
