import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { beforeEach, describe, it } from "node:test";
import { assert } from "chai";
import { MockAgent, setGlobalDispatcher } from "undici";
import { ZUPLO_VERSION_CHECK_FILE } from "../common/constants.js";
import { warnIfOutdatedVersion } from "../common/outdated.js";
import { ZUPLO_XDG_STATE_HOME } from "../common/xdg/lib.js";
const versionCheckPath = join(ZUPLO_XDG_STATE_HOME, ZUPLO_VERSION_CHECK_FILE);
process.env.ZUPLO_OVERRIDE_CI_TO_TEST = "true";
describe("Outdated CLI check", function () {
    let mockAgent;
    beforeEach(() => {
        mockAgent = new MockAgent();
        mockAgent.disableNetConnect();
        mockAgent
            .get("https://raw.githubusercontent.com")
            .intercept({
            path: "/zuplo/zuplo/main/packages/zuplo/package.json",
            method: "GET",
        })
            .reply(200, {
            name: "zuplo",
            dependencies: {
                "@zuplo/cli": "1.109.0",
            },
        });
        setGlobalDispatcher(mockAgent);
    });
    it("should warn on outdated version", async function () {
        await rm(versionCheckPath, { recursive: true, force: true });
        const result = await warnIfOutdatedVersion("1.0.0");
        assert.isTrue(result);
        assert.equal(mockAgent.pendingInterceptors.length, 0);
    });
    it("should not warn if current version", async function () {
        const result = await warnIfOutdatedVersion("1.109.0");
        assert.isFalse(result);
    });
    it("should not warn if still has cached result", async function () {
        const state = { lastCheck: Date.now() - 1000, latestVersion: "1.108.0" };
        await writeFile(versionCheckPath, JSON.stringify(state), "utf-8");
        const result = await warnIfOutdatedVersion("1.108.0");
        assert.isFalse(result);
    });
    it("should warn when time expired on outdated version", async function () {
        const state = {
            lastCheck: Date.now() - 1000 * 60 * 60 * 24 - 100,
            latestVersion: "1.0.0",
        };
        await writeFile(versionCheckPath, JSON.stringify(state), "utf-8");
        const result = await warnIfOutdatedVersion("1.0.0");
        assert.isTrue(result);
        assert.equal(mockAgent.pendingInterceptors.length, 0);
    });
    it("should handle invalid state", async function () {
        await writeFile(versionCheckPath, "hello", "utf-8");
        const result = await warnIfOutdatedVersion("0.0.1");
        assert.isTrue(result);
        assert.equal(mockAgent.pendingInterceptors.length, 0);
    });
});
//# sourceMappingURL=outdated.test.js.map