import { describe, expect, it } from "vitest";

import { evaluatePermission, isDangerousPermission } from "./permission-policy";

const allowOption = { id: "allow", title: "Allow" };
const denyOption = { id: "deny", title: "Deny" };

describe("isDangerousPermission", () => {
  it("flags merge operations", () => {
    expect(
      isDangerousPermission({
        requestId: "r1",
        toolCall: { title: "git merge main" },
      })
    ).toBe(true);
  });

  it("flags production deployment", () => {
    expect(
      isDangerousPermission({
        requestId: "r2",
        toolCall: { title: "deploy to production" },
      })
    ).toBe(true);
  });

  it("flags secret access", () => {
    expect(
      isDangerousPermission({
        requestId: "r3",
        toolCall: { title: "read secrets" },
      })
    ).toBe(true);
  });

  it("flags credential access", () => {
    expect(
      isDangerousPermission({
        requestId: "r4",
        toolCall: { title: "access credentials" },
      })
    ).toBe(true);
  });

  it("does not flag safe operations", () => {
    expect(
      isDangerousPermission({
        requestId: "r5",
        toolCall: { title: "run tests" },
      })
    ).toBe(false);
  });

  it("does not flag file edits", () => {
    expect(
      isDangerousPermission({
        requestId: "r6",
        toolCall: { title: "edit src/index.ts" },
      })
    ).toBe(false);
  });
});

describe("evaluatePermission", () => {
  it("allows safe operations and picks allow option", () => {
    const decision = evaluatePermission({
      options: [allowOption, denyOption],
      requestId: "r1",
      toolCall: { title: "run bun test" },
    });
    expect(decision.allow).toBe(true);
    expect(decision.optionId).toBe("allow");
  });

  it("denies dangerous operations and picks deny option", () => {
    const decision = evaluatePermission({
      options: [allowOption, denyOption],
      requestId: "r2",
      toolCall: { title: "git merge main" },
    });
    expect(decision.allow).toBe(false);
    expect(decision.optionId).toBe("deny");
  });

  it("falls back to last option when no explicit deny exists", () => {
    const decision = evaluatePermission({
      options: [
        { id: "ok", title: "OK" },
        { id: "cancel", title: "Cancel" },
      ],
      requestId: "r3",
      toolCall: { title: "deploy to production" },
    });
    expect(decision.allow).toBe(false);
    expect(decision.optionId).toBe("cancel");
  });

  it("handles empty options", () => {
    const decision = evaluatePermission({
      options: [],
      requestId: "r4",
      toolCall: { title: "run tests" },
    });
    expect(decision.allow).toBe(true);
    expect(decision.optionId).toBeUndefined();
  });
});
