import * as os from "os";
import { Injectable } from "@nestjs/common";

@Injectable()
export class HealthService {
  private totalTime?: number;
  private usedTime?: number;
  private currentUsage?: number;

  constructor() {
    setInterval(() => this.updateCpuUsage(), 1000);
  }

  private updateCpuUsage() {
    const cpus = os.cpus();

    const totalTime = cpus.reduce(
      (acc, cpu) =>
        acc + Object.values(cpu.times).reduce((acc, time) => acc + time, 0),
      0
    );

    const usedTime = cpus.reduce(
      (acc, cpu) => acc + cpu.times.user + cpu.times.sys,
      0
    );

    if (this.totalTime && this.usedTime) {
      const totalDiff = totalTime - this.totalTime;
      const usedDiff = usedTime - this.usedTime;

      this.currentUsage = (usedDiff / totalDiff) * 100;
    }

    this.totalTime = totalTime;
    this.usedTime = usedTime;
  }

  getServerCpuUsage(): number {
    return this.currentUsage ?? 0;
  }
}
