import { mkdtemp, readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { JsonSearchHistoryStorage } from "../desktop/historyStorage.js";
import type { SearchHistory } from "../shared/contract.js";

const history: SearchHistory = { schemaVersion: 1, entries: [{ query: "W71252", canonical: "W71252", searchedAt: 1 }] };

describe("JsonSearchHistoryStorage", () => {
  it("returns empty before saving and atomically persists history", async () => {
    const dir = await mkdtemp(join(tmpdir(), "comparator-history-"));
    const path = join(dir, "nested", "search-history.json");
    const storage = new JsonSearchHistoryStorage(path);
    await expect(storage.loadResponse()).resolves.toEqual({ history: null, updatedAt: null });
    await expect(storage.set(history, 1234)).resolves.toBe(1234);
    await expect(storage.loadResponse()).resolves.toEqual({ history, updatedAt: 1234 });
    expect(JSON.parse(await readFile(path, "utf8"))).toEqual({ history, updatedAt: 1234 });
  });

  it("rejects a malformed file", async () => {
    const dir = await mkdtemp(join(tmpdir(), "comparator-history-"));
    const path = join(dir, "search-history.json");
    await writeFile(path, "{}\n");
    await expect(new JsonSearchHistoryStorage(path).loadResponse()).rejects.toThrow("invalid search-history file");
  });
});
