/**
 * Windows service uninstaller (used by Inno Setup uninstall).
 */
const path = require("path");
const fs = require("fs");
const { execSync } = require("child_process");

const EXIT_OK = 0;
const EXIT_ERR = 1;

if (process.platform !== "win32") {
  process.exit(EXIT_OK);
}

const installDir =
  process.env.SIRAYA_INSTALL_DIR ||
  path.join(process.env.ProgramFiles || "C:\\Program Files", "Siraya", "Printer");
const dataDir =
  process.env.SIRAYA_DATA_DIR ||
  path.join(process.env.ProgramData || "C:\\ProgramData", "Siraya", "Printer");
const serviceName = "SirayaPrinterService";
const keepData = process.env.SIRAYA_KEEP_DATA === "1";

function removeFirewallRule() {
  try {
    execSync(
      'netsh advfirewall firewall delete rule name="Siraya Printer (localhost)"',
      { stdio: "ignore" },
    );
  } catch {
    /* ignore */
  }
}

function removeDataDir() {
  if (keepData || !fs.existsSync(dataDir)) return;
  fs.rmSync(dataDir, { recursive: true, force: true });
}

function main() {
  try {
    execSync(`net stop ${serviceName}`, { stdio: "ignore" });
  } catch {
    /* ignore */
  }

  const script = path.join(installDir, "index.js");
  if (!fs.existsSync(script)) {
    try {
      execSync(`sc delete ${serviceName}`, { stdio: "ignore" });
    } catch {
      /* ignore */
    }
    removeFirewallRule();
    removeDataDir();
    process.exit(EXIT_OK);
  }

  const Service = require(path.join(
    installDir,
    "node_modules",
    "node-windows",
  )).Service;

  const svc = new Service({
    name: serviceName,
    script,
    workingDirectory: installDir,
  });

  let done = false;
  const finish = (code) => {
    if (done) return;
    done = true;
    removeFirewallRule();
    removeDataDir();
    process.exit(code);
  };

  svc.on("uninstall", () => {
    console.log("Service removed:", serviceName);
    finish(EXIT_OK);
  });

  svc.on("error", (err) => {
    console.error("Uninstall error:", err);
    try {
      execSync(`sc delete ${serviceName}`, { stdio: "ignore" });
    } catch {
      /* ignore */
    }
    finish(EXIT_ERR);
  });

  setTimeout(() => finish(EXIT_ERR), 60000);
  svc.uninstall();
}

main();
