import AppResponse from '@/response/app-response';
import { Injectable } from '@nestjs/common';
import { exec } from 'child_process';
@Injectable()
export class DashboardService {
  constructor() {}

  private readonly tool_name = 'auto-bid-tool';

  async resetProcessByName(toolName: string): Promise<string> {
    return new Promise((resolve, reject) => {
      // Lấy danh sách process đang chạy
      exec('pm2 jlist', (error, stdout, stderr) => {
        if (error) {
          return reject(`Error get list process: ${stderr}`);
        }

        try {
          const processList = JSON.parse(stdout);
          const targetProcess = processList.find(
            (proc: any) => proc.name === toolName,
          );

          if (!targetProcess) {
            return reject(`Not found process for name "${toolName}"`);
          }

          const pmId = targetProcess.pm_id;

          // Restart process theo pm_id
          exec(`pm2 restart ${pmId}`, (err, out, errOut) => {
            if (err) {
              return reject(`Error restart process: ${errOut}`);
            }
            resolve(`Restarted process "${toolName}" with pm_id ${pmId}`);
          });
        } catch (parseErr) {
          reject(`Error parse JSON output: ${parseErr}`);
        }
      });
    });
  }

  async getStatusProcessByName(toolName: string): Promise<string> {
    return new Promise((resolve, reject) => {
      exec('pm2 jlist', (error, stdout, stderr) => {
        if (error) {
          return reject(`Error get list process: ${stderr}`);
        }
  
        try {
          const processList = JSON.parse(stdout);
          const targetProcess = processList.find(
            (proc: any) => proc.name === toolName,
          );
  
          if (!targetProcess) {
            return reject(`Not found process for name "${toolName}"`);
          }
  
          const status = targetProcess.pm2_env?.status || 'unknown';
          return resolve(status); // Trả về: 'online', 'stopped', 'errored', etc.
  
        } catch (parseErr) {
          reject(`Error parse JSON output: ${parseErr}`);
        }
      });
    });
  }
  

  async shutdownProcessByName(toolName: string): Promise<string> {
    return new Promise((resolve, reject) => {
      // Lấy danh sách process đang chạy
      exec('pm2 jlist', (error, stdout, stderr) => {
        if (error) {
          return reject(`Error get list process: ${stderr}`);
        }

        try {
          const processList = JSON.parse(stdout);
          const targetProcess = processList.find(
            (proc: any) => proc.name === toolName,
          );

          if (!targetProcess) {
            return reject(`Not found process for name "${toolName}"`);
          }

          const pmId = targetProcess.pm_id;

          // Restart process theo pm_id
          exec(`pm2 stop ${pmId}`, (err, out, errOut) => {
            if (err) {
              return reject(`Error restart process: ${errOut}`);
            }
            resolve(`Restarted process "${toolName}" with pm_id ${pmId}`);
          });
        } catch (parseErr) {
          reject(`Error parse JSON output: ${parseErr}`);
        }
      });
    });
  }

  async resetTool() {
    try {
      await this.resetProcessByName(this.tool_name);

      return AppResponse.toResponse(true);
    } catch (error) {
      return AppResponse.toResponse(false);
    }
  }

  async shutdownTool() {
    try {
      await this.shutdownProcessByName(this.tool_name);

      return AppResponse.toResponse(true);
    } catch (error) {
      return AppResponse.toResponse(false);
    }
  }


  async statusTool() {
    try {
     const result = await this.getStatusProcessByName(this.tool_name);

      return AppResponse.toResponse(result);
    } catch (error) {
      return AppResponse.toResponse(false);
    }
  }
}
