import { existsSync, unlinkSync } from "node:fs";
import { paths } from "../../lifecycle/paths.ts";
import { readPid, removePid, isAlive } from "../../lifecycle/pid.ts";

export async function cmdStop(_flags: Record<string, string | true>, verbose = false): Promise<number> {
  const pid = readPid(paths.pidFile());
  if (pid === null) { if (!verbose) { console.log("ok"); } else { console.log("fewtok not running"); } return 0; }
  if (!isAlive(paths.pidFile())) {
    removePid(paths.pidFile());
    if (existsSync(paths.portFile())) unlinkSync(paths.portFile());
    if (!verbose) { console.log("ok"); } else { console.log("fewtok was not actually running, cleaned pid file"); }
    return 0;
  }
  try {
    process.kill(pid, "SIGTERM");
    if (!verbose) { console.log("ok"); } else { console.log(`stopped fewtok (pid ${pid})`); }
  } catch (e) {
    if (!verbose) { console.log("err=stop-failed"); } else { console.error("failed to stop:", (e as Error).message); }
    return 1;
  }
  removePid(paths.pidFile());
  if (existsSync(paths.portFile())) unlinkSync(paths.portFile());
  return 0;
}
