import assert from "node:assert/strict";
import test from "node:test";

import {
  assertMessagePermissionsAllowed,
  fullPermissionCeiling,
  publicPermissionProfilesWithinCeiling
} from "./permission-ceiling.js";

test("installed full ceiling allows every built-in chat permission", () => {
  for (const options of [
    { permissionProfile: ":read-only", approvalPolicy: "untrusted" },
    { permissionProfile: ":workspace", approvalPolicy: "on-failure" },
    { permissionProfile: ":workspace", approvalPolicy: "on-request" },
    { permissionProfile: ":danger-full-access", approvalPolicy: "never" }
  ]) {
    assert.doesNotThrow(() => assertMessagePermissionsAllowed(options, fullPermissionCeiling));
  }
});

test("browser input cannot exceed a locally reduced ceiling", () => {
  const ceiling = { permissionProfile: ":workspace", approvalPolicy: "on-request" };

  assert.throws(
    () => assertMessagePermissionsAllowed({ permissionProfile: ":danger-full-access" }, ceiling),
    (error) => error.message === "permission_ceiling_exceeded" && error.status === 400
  );
  assert.throws(
    () => assertMessagePermissionsAllowed({ approvalPolicy: "never" }, ceiling),
    (error) => error.message === "permission_ceiling_exceeded" && error.status === 400
  );
});

test("unknown permission input fails closed instead of reaching Codex", () => {
  for (const options of [
    { permissionProfile: ":browser-invented" },
    { approvalPolicy: "always-allow" },
    { sandbox: "host-unrestricted" }
  ]) {
    assert.throws(
      () => assertMessagePermissionsAllowed(options, fullPermissionCeiling),
      (error) => error.message === "permission_not_allowed" && error.status === 400
    );
  }
});

test("capability projection hides profiles above the local ceiling", () => {
  const profiles = [
    { id: ":read-only", allowed: true },
    { id: ":workspace", allowed: true },
    { id: ":danger-full-access", allowed: true },
    { id: ":custom-unknown", allowed: true }
  ];

  assert.deepEqual(
    publicPermissionProfilesWithinCeiling(profiles, {
      permissionProfile: ":workspace",
      approvalPolicy: "on-request"
    }).map((profile) => profile.id),
    [":read-only", ":workspace"]
  );
});
