import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import { mkdtemp, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { atomicWriteFile, readTextFile } from "../../src/utils/fileStore.js";

describe("fileStore", () => {
  const originalDateNow = Date.now;
  let tempDir: string;

  beforeEach(async () => {
    tempDir = await mkdtemp(join(tmpdir(), "tjwater-file-store-"));
  });

  afterEach(async () => {
    Date.now = originalDateNow;
    await rm(tempDir, { force: true, recursive: true });
  });

  it("uses unique temp paths for concurrent writes in the same millisecond", async () => {
    Date.now = () => 1_801_578_600_000;
    const path = join(tempDir, "state.json");
    const values = Array.from({ length: 24 }, (_, index) => `value-${index}`);

    await Promise.all(values.map((value) => atomicWriteFile(path, value)));

    const written = await readTextFile(path);
    expect(written).not.toBeNull();
    expect(values).toContain(written as string);
    expect((await readdir(tempDir)).filter((name) => name.endsWith(".tmp"))).toEqual([]);
  });
});
