import { access, mkdir, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Readable } from "node:stream";
import { afterEach, describe, expect, it } from "vitest";
import { writeNewWorkspaceFileNoFollow } from "../../src/security/workspaceFiles.js";

const roots: string[] = [];

describe("inbound workspace file limits", () => {
  const itOnLinux = process.platform === "linux" ? it : it.skip;
  afterEach(async () => {
    await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  });

  itOnLinux("fails and removes the partial file when the byte limit is exceeded", async () => {
    const root = await mkdtemp(join(tmpdir(), "cph-workspace-limit-"));
    roots.push(root);
    const workspace = join(root, "project");
    await mkdir(workspace);

    await expect(writeNewWorkspaceFileNoFollow(
      root,
      workspace,
      "too-large.bin",
      Readable.from([Buffer.from("1234")]),
      3,
    )).rejects.toMatchObject({ reason: "limit" });
    await expect(access(join(workspace, "too-large.bin"))).rejects.toMatchObject({ code: "ENOENT" });
  });
});
