import { describe, it, expect, beforeEach, afterEach } from "vitest";
import fs from "fs";
import os from "os";
import path from "path";
import { writeIpcFile, readJsonFile } from "../src/ipc.js";

let tmpDir: string;

beforeEach(() => {
  tmpDir = path.join(os.tmpdir(), `treehouse-test-${Math.random().toString(36).slice(2)}`);
  fs.mkdirSync(tmpDir, { recursive: true });
});

afterEach(() => {
  fs.rmSync(tmpDir, { recursive: true, force: true });
});

describe("writeIpcFile", () => {
  it("writes a JSON file and returns the filename", () => {
    const data = { type: "test", value: 42 };
    const filename = writeIpcFile(tmpDir, data);
    expect(filename).toMatch(/^\d+-[a-z0-9]+\.json$/);
    const filepath = path.join(tmpDir, filename);
    expect(fs.existsSync(filepath)).toBe(true);
    const parsed = JSON.parse(fs.readFileSync(filepath, "utf8"));
    expect(parsed).toEqual(data);
  });

  it("creates the directory if it does not exist", () => {
    const subDir = path.join(tmpDir, "nested", "dir");
    const filename = writeIpcFile(subDir, { hello: "world" });
    expect(fs.existsSync(path.join(subDir, filename))).toBe(true);
  });

  it("writes atomically (no .tmp file left behind)", () => {
    writeIpcFile(tmpDir, { x: 1 });
    const files = fs.readdirSync(tmpDir);
    expect(files.every((f) => !f.endsWith(".tmp"))).toBe(true);
  });
});

describe("readJsonFile", () => {
  it("reads and parses a JSON file", () => {
    const data = { foo: "bar" };
    const filepath = path.join(tmpDir, "test.json");
    fs.writeFileSync(filepath, JSON.stringify(data));
    expect(readJsonFile(filepath)).toEqual(data);
  });

  it("returns null for missing files", () => {
    expect(readJsonFile(path.join(tmpDir, "nonexistent.json"))).toBeNull();
  });
});
