import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createThreadPreferencesStore } from "./thread-preferences.js";

test("thread pins persist by owner and thread without leaking paths", async () => {
  const dir = await mkdtemp(join(tmpdir(), "thread-preferences-"));
  try {
    const store = createThreadPreferencesStore(dir);
    await store.setPinned("account-a", "same", true);
    await store.setPinned("account-b", "same", true);
    await store.setPinned("account-a", "same", false);

    assert.equal(await store.isPinned("account-a", "same"), false);
    assert.equal(await store.isPinned("account-b", "same"), true);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
});

test("deleted thread tombstones persist and clear pins", async () => {
  const dir = await mkdtemp(join(tmpdir(), "thread-preferences-"));
  try {
    const store = createThreadPreferencesStore(dir);
    await store.setPinned("account-a", "thread-1", true);
    await store.setDeleted("account-a", "thread-1", true);

    assert.deepEqual(await store.deletedKeys(), new Set(["account-a:thread-1"]));
    assert.equal(await store.isPinned("account-a", "thread-1"), false);

    await store.setDeleted("account-a", "thread-1", false);
    assert.deepEqual(await store.deletedKeys(), new Set());
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
});
