import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, rm, stat } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { createBrowsedFolder } from "./folder-browser.js";

test("creates a named child folder from an opaque parent and opens it", async () => {
  const root = await mkdtemp(join(tmpdir(), "folder-browser-"));
  let openedPath;
  try {
    const result = await createBrowsedFolder({}, "opaque-parent", "CRUBLY", {
      resolveFolder: () => root,
      openFolder: async (_config, path) => {
        openedPath = path;
        return { current: "CRUBLY", currentId: "opaque-child", folders: [] };
      }
    });
    assert.equal((await stat(join(root, "CRUBLY"))).isDirectory(), true);
    assert.equal(openedPath, join(root, "CRUBLY"));
    assert.deepEqual(result, { current: "CRUBLY", currentId: "opaque-child", folders: [] });
  } finally {
    await rm(root, { recursive: true, force: true });
  }
});

test("rejects invalid child folder names before writing", async () => {
  await assert.rejects(
    createBrowsedFolder({}, "opaque-parent", "../escape", { resolveFolder: () => "C:\\Projects" }),
    (error) => error.message === "invalid_project_name" && error.status === 400
  );
});
