import { mkdtemp, rm } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { openDatabase, closeDatabase } from "../../database.js";
import { createProject } from "../projects.js";
import { initFsState, getSeq, updateSeq, incrementSeq, resetSeq } from "../fs-state.js";
describe("fs-state repository", () => {
    let tempDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-fsstate-test-"));
        dbPath = join(tempDir, "daemon.db");
        closeDatabase();
        openDatabase(dbPath);
        // Create a project to use as FK reference
        const project = createProject("test-project", "/tmp/test-project");
        projectId = project.project_id;
    });
    afterEach(async () => {
        closeDatabase();
        await rm(tempDir, { recursive: true, force: true });
    });
    it("should initialize fs_state for new project", () => {
        initFsState(projectId);
        const seq = getSeq(projectId);
        expect(seq).toBe(0);
    });
    it("should not overwrite existing fs_state on init", () => {
        initFsState(projectId);
        updateSeq(projectId, 42);
        // Re-initializing should not reset
        initFsState(projectId);
        expect(getSeq(projectId)).toBe(42);
    });
    it("should return 0 for project with no fs_state entry", () => {
        const seq = getSeq(projectId);
        expect(seq).toBe(0);
    });
    it("should get last sequence number", () => {
        updateSeq(projectId, 10);
        expect(getSeq(projectId)).toBe(10);
    });
    it("should update sequence number", () => {
        updateSeq(projectId, 5);
        expect(getSeq(projectId)).toBe(5);
        updateSeq(projectId, 100);
        expect(getSeq(projectId)).toBe(100);
    });
    it("should create entry on update if not exists", () => {
        // No initFsState called, but updateSeq should upsert
        updateSeq(projectId, 7);
        expect(getSeq(projectId)).toBe(7);
    });
    it("should increment sequence number", () => {
        initFsState(projectId);
        const seq1 = incrementSeq(projectId);
        expect(seq1).toBe(1);
        const seq2 = incrementSeq(projectId);
        expect(seq2).toBe(2);
        const seq3 = incrementSeq(projectId);
        expect(seq3).toBe(3);
    });
    it("should create entry on increment if not exists", () => {
        const seq = incrementSeq(projectId);
        expect(seq).toBe(1);
    });
    it("should reset sequence counter", () => {
        updateSeq(projectId, 50);
        expect(getSeq(projectId)).toBe(50);
        resetSeq(projectId);
        // After reset, getSeq returns 0 (no entry)
        expect(getSeq(projectId)).toBe(0);
    });
});
//# sourceMappingURL=fs-state.test.js.map