import { afterEach, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { compareVersions, notifyIfUpdateAvailable } from "../src/update-notifier.ts";

const originalCache = process.env.WRNEXUS_UPDATE_CACHE;

afterEach(() => {
  if (originalCache === undefined) delete process.env.WRNEXUS_UPDATE_CACHE;
  else process.env.WRNEXUS_UPDATE_CACHE = originalCache;
});

test("compareVersions compares stable semantic versions", () => {
  expect(compareVersions("0.2.14", "0.2.13")).toBe(1);
  expect(compareVersions("0.2.13", "0.2.13")).toBe(0);
  expect(compareVersions("0.2.12", "0.2.13")).toBe(-1);
});

test("cached update checks suggest the exact upgrade command", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-notify-"));
  const cache = join(root, "update.json");
  process.env.WRNEXUS_UPDATE_CACHE = cache;
  writeFileSync(cache, JSON.stringify({ checkedAt: Date.now(), latest: "0.2.14" }));
  const messages: string[] = [];
  const original = console.log;
  console.log = (...parts) => messages.push(parts.join(" "));

  try {
    notifyIfUpdateAvailable("0.2.13", "dev");
    expect(messages.join("\n")).toContain("WRNexusJS 0.2.13 → 0.2.14");
    expect(messages.join("\n")).toContain("wrnexus update --latest");
  } finally {
    console.log = original;
    rmSync(root, { recursive: true, force: true });
  }
});
