import { sha256Json } from "./crypto";
import type { JsonObject } from "./types";

export type Scenario = "mediated_append" | "refused_append";

export interface PolicyDecision {
  decision: "PERMIT" | "REFUSE";
  rationale_codes: string[];
  policy_digest: string;
  authzen: {
    decision: boolean;
    context: {
      reason_admin: string;
    };
  };
}

export const POLICY_DOCUMENT = {
  profile: "bulla.control-plane-alpha/0.1-experimental",
  policy_id: "policy://bulla-control-plane-alpha/synthetic-authzen",
  operation: "sandbox.append",
  scenarios: {
    mediated_append: "PERMIT",
    refused_append: "REFUSE",
  },
  values: {
    mediated_append: "alpha-mediated",
    direct_effect: "alpha-direct-bypass",
  },
} as const satisfies JsonObject;

export async function policyDigest(): Promise<string> {
  return sha256Json(POLICY_DOCUMENT);
}

export async function decide(scenario: Scenario): Promise<PolicyDecision> {
  const permit = scenario === "mediated_append";
  return {
    decision: permit ? "PERMIT" : "REFUSE",
    rationale_codes: [permit ? "FIXED_OPERATION_ALLOWED" : "CONFIGURED_REFUSAL"],
    policy_digest: await policyDigest(),
    authzen: {
      decision: permit,
      context: {
        reason_admin: permit
          ? "The closed synthetic policy permits the fixed sandbox.append scenario."
          : "The closed synthetic policy refuses the configured no-op scenario.",
      },
    },
  };
}
