import { describe, it, expect, beforeEach } from "bun:test";
import { isShuttingDown, setShuttingDown, incrementTransactions, decrementTransactions, getActiveTransactions, waitForTransactions } from "./shutdown";

describe("shutdown logic", () => {
    beforeEach(() => {
        setShuttingDown(false);
        while (getActiveTransactions() > 0) {
            decrementTransactions();
        }
    });

    it("should initialize with shuttingDown as false", () => {
        expect(isShuttingDown()).toBe(false);
    });

    it("should update shuttingDown state", () => {
        setShuttingDown(true);
        expect(isShuttingDown()).toBe(true);
    });

    it("should track active transactions", () => {
        expect(getActiveTransactions()).toBe(0);
        incrementTransactions();
        expect(getActiveTransactions()).toBe(1);
        decrementTransactions();
        expect(getActiveTransactions()).toBe(0);
    });

    it("should wait for transactions to complete", async () => {
        incrementTransactions();

        const start = Date.now();
        const waitPromise = waitForTransactions(1000);

        // Simulate completion after 200ms
        setTimeout(() => {
            decrementTransactions();
        }, 200);

        await waitPromise;
        const duration = Date.now() - start;

        expect(duration).toBeGreaterThanOrEqual(200);
        expect(getActiveTransactions()).toBe(0);
    });

    it("should timeout if transactions never complete", async () => {
        incrementTransactions();
        const start = Date.now();
        await waitForTransactions(500);
        const duration = Date.now() - start;

        expect(duration).toBeGreaterThanOrEqual(500);
        expect(getActiveTransactions()).toBe(1); // Still 1 because we didn't decrement
    });
});
