//! §9.4 Service Interceptors, end to end via `pic` — the KV allow/deny slice.
//!
//! A `[[interceptors]]` marker binds a script to run BEFORE `kv::set`/`delete`.
//! The interceptor reads the operation context (`ctx.request.body` — service,
//! action, collection, key, value) and returns `#{ allowed: bool, reason }`; a
//! `false` denies the op (the write never happens, the caller gets an error).
//! A group's interceptor is inherited by a descendant app; from §9.4 M2 the
//! `before` markers on the chain run as an ORDERED CHAIN (ancestor→app), so a
//! group guard and an app guard both run — a single deny short-circuits.

use std::fs;

use tempfile::TempDir;

use crate::common;
use crate::common::cleanup::{AppGuard, GroupGuard};

fn manifest_dir() -> TempDir {
    let dir = TempDir::new().expect("tempdir");
    fs::create_dir_all(dir.path().join("scripts")).expect("scripts dir");
    dir
}

fn app_script_id(env: &common::TestEnv, app: &str, name: &str) -> String {
    let ls = common::pic_as(env)
        .args(["scripts", "ls", "--app", app])
        .output()
        .expect("scripts ls");
    let table = String::from_utf8(ls.stdout).unwrap();
    table
        .lines()
        .map(common::cells)
        .find(|c| c.get(2) == Some(&name))
        .and_then(|c| c.first().map(|s| (*s).to_string()))
        .unwrap_or_else(|| panic!("script `{name}` not found:\n{table}"))
}

fn invoke_body(env: &common::TestEnv, id: &str) -> serde_json::Value {
    let out = common::pic_as(env)
        .args(["scripts", "invoke", id])
        .output()
        .expect("scripts invoke");
    assert!(
        out.status.success(),
        "invoke failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    serde_json::from_slice(&out.stdout).expect("invoke body is JSON")
}

/// A guard that denies a `kv::set` of the key `"secret"` and allows everything
/// else, reading the op context from `ctx.request.body`.
const GUARD: &str = r#"
let op = ctx.request.body;
if op.action == "set" && op.key == "secret" {
    #{ allowed: false, reason: "the `secret` key is protected" }
} else {
    #{ allowed: true }
}
"#;

/// A writer that tries a denied set (caught), then a permitted set.
const WRITER: &str = r#"
let denied = false;
try { kv::collection("c").set("secret", 1); } catch(e) { denied = true; }
kv::collection("c").set("ok", 2);
#{ denied: denied }
"#;

/// A permissive guard an app might define to try to SHADOW a group's guard by
/// re-using its script name. The seal must make the group's guard win anyway.
const PERMISSIVE_GUARD: &str = r#"#{ allowed: true }"#;

/// A guard that returns a map WITHOUT an `allowed` key — a malformed verdict.
/// The fail-closed contract must treat this as a deny.
const NO_VERDICT_GUARD: &str = r#"#{ note: "forgot to return allowed" }"#;

/// A writer over a group SHARED collection (finding 1: the shared handle must
/// be intercepted too, not just `kv::collection`).
const SHARED_WRITER: &str = r#"
let denied = false;
try { kv::shared_collection("catalog").set("secret", 1); } catch(e) { denied = true; }
kv::shared_collection("catalog").set("ok", 2);
#{ denied: denied }
"#;

/// A writer that only tries a single (guarded) set.
const ANY_WRITER: &str = r#"
let denied = false;
try { kv::collection("c").set("anything", 1); } catch(e) { denied = true; }
#{ denied: denied }
"#;

#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn app_interceptor_denies_a_guarded_kv_write_and_allows_others() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let app = common::unique_slug("ic-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();

    // One apply deploys the guard + writer scripts AND registers the marker.
    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), GUARD).unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), WRITER).unwrap();
    fs::write(
        dir.path().join("picloud.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"IC\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("picloud.toml"))
        .assert()
        .success();

    // The writer's guarded set is denied (caught), the permitted set goes through.
    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "denied": true }),
        "the `secret` set must be denied by the interceptor"
    );

    // `ok` was written; `secret` was not (the write never ran).
    let ok = String::from_utf8(
        common::pic_as(&env)
            .args(["kv", "get", "--app", &app, "--collection", "c", "ok"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(ok.contains('2'), "the allowed write must persist:\n{ok}");
    let secret = common::pic_as(&env)
        .args(["kv", "get", "--app", &app, "--collection", "c", "secret"])
        .output()
        .unwrap();
    let secret_out = String::from_utf8_lossy(&secret.stdout);
    assert!(
        secret_out.trim() == "null" || secret_out.trim() == "()" || secret_out.trim().is_empty(),
        "the denied write must NOT persist, got: {secret_out}"
    );
}

#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn a_group_interceptor_is_inherited_by_a_descendant_app() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let group = common::unique_slug("icg-grp");
    let app = common::unique_slug("icg-app");
    let _g = GroupGuard::new(&env.url, &env.token, &group);
    common::pic_as(&env)
        .args(["groups", "create", &group])
        .assert()
        .success();

    // The GROUP owns the guard script + the interceptor marker.
    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), GUARD).unwrap();
    fs::write(
        dir.path().join("group.toml"),
        format!(
            "[group]\nslug = \"{group}\"\nname = \"ICG\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("group.toml"))
        .assert()
        .success();

    // An app UNDER the group inherits the interceptor (nearest-owner-wins), even
    // though the marker + guard live on the group.
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app, "--group", &group])
        .assert()
        .success();
    fs::write(dir.path().join("scripts/writer.rhai"), WRITER).unwrap();
    fs::write(
        dir.path().join("app.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"ICApp\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("app.toml"))
        .assert()
        .success();

    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "denied": true }),
        "a descendant app must inherit the group's interceptor"
    );
}

/// The seal (finding 2): a group's interceptor script is resolved AT THE GROUP,
/// so a descendant app cannot defeat a mandatory guard by defining a permissive
/// script of the same name. The app declares no interceptor of its own — it just
/// shadows the script name — and the group's strict guard must still win.
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn a_descendant_cannot_shadow_a_group_interceptor_by_reusing_the_script_name() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let group = common::unique_slug("seal-grp");
    let app = common::unique_slug("seal-app");
    let _g = GroupGuard::new(&env.url, &env.token, &group);
    common::pic_as(&env)
        .args(["groups", "create", &group])
        .assert()
        .success();

    // The group owns the strict guard + the interceptor marker.
    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), GUARD).unwrap();
    fs::write(
        dir.path().join("group.toml"),
        format!(
            "[group]\nslug = \"{group}\"\nname = \"Seal\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("group.toml"))
        .assert()
        .success();

    // The app under the group defines its OWN script named `guard` (permissive)
    // but declares NO interceptor. The seal must keep the group's guard in force.
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app, "--group", &group])
        .assert()
        .success();
    fs::write(
        dir.path().join("scripts/guard_permissive.rhai"),
        PERMISSIVE_GUARD,
    )
    .unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), WRITER).unwrap();
    fs::write(
        dir.path().join("app.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"SealApp\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard_permissive.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("app.toml"))
        .assert()
        .success();

    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "denied": true }),
        "the group's guard is sealed — a same-named app script must NOT shadow it"
    );
}

/// Finding 1: a `(kv, set)` interceptor covers group SHARED-collection writes,
/// not just `kv::collection`. Otherwise `kv::shared_collection(...).set(...)`
/// would be a silent bypass of the guard.
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn an_interceptor_guards_shared_collection_writes() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let group = common::unique_slug("shc-grp");
    let app = common::unique_slug("shc-app");
    let _g = GroupGuard::new(&env.url, &env.token, &group);
    common::pic_as(&env)
        .args(["groups", "create", &group])
        .assert()
        .success();

    // The group owns a shared `catalog` collection, the guard, and the marker.
    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), GUARD).unwrap();
    fs::write(
        dir.path().join("group.toml"),
        format!(
            "[group]\nslug = \"{group}\"\nname = \"Shc\"\n\ncollections = [\"catalog\"]\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("group.toml"))
        .assert()
        .success();

    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app, "--group", &group])
        .assert()
        .success();
    fs::write(dir.path().join("scripts/shared_writer.rhai"), SHARED_WRITER).unwrap();
    fs::write(
        dir.path().join("app.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"ShcApp\"\n\n\
             [[scripts]]\nname = \"shared_writer\"\nfile = \"scripts/shared_writer.rhai\"\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("app.toml"))
        .assert()
        .success();

    let body = invoke_body(&env, &app_script_id(&env, &app, "shared_writer"));
    assert_eq!(
        body,
        serde_json::json!({ "denied": true }),
        "the shared-collection write of `secret` must be denied by the interceptor"
    );
}

/// Finding 4: the verdict is fail-closed. An interceptor that returns a map with
/// no `allowed` key (a malformed verdict) DENIES the op — a guard must never
/// allow by omission.
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn a_malformed_verdict_fails_closed() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let app = common::unique_slug("fc-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();

    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), NO_VERDICT_GUARD).unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), ANY_WRITER).unwrap();
    fs::write(
        dir.path().join("picloud.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"FC\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("picloud.toml"))
        .assert()
        .success();

    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "denied": true }),
        "a verdict map with no `allowed` key must fail closed (deny)"
    );
}

// --- §9.4 M8: docs (a representative non-KV service) -----------------------

/// A `(docs, create)` guard that denies creating a doc whose `data.kind` is
/// `"secret"`, reading the written value from `ctx.request.body.value`. Proves a
/// non-KV service funnels through the same before/after machinery and that the
/// created document's data is surfaced to the hook.
const DOCS_GUARD: &str = r#"
let op = ctx.request.body;
if op.action == "create" && op.value.kind == "secret" {
    #{ allowed: false, reason: "secret docs are protected" }
} else {
    #{ allowed: true }
}
"#;

/// A writer that tries a denied `docs::create` (caught), then a permitted one,
/// and reports how many docs actually landed in the collection.
const DOCS_WRITER: &str = r#"
let denied = false;
try { docs::collection("c").create(#{ kind: "secret", n: 1 }); } catch(e) { denied = true; }
docs::collection("c").create(#{ kind: "public", n: 2 });
let all = docs::collection("c").find(#{});
#{ denied: denied, count: all.len() }
"#;

/// §9.4 M8: `[[interceptors]] service = "docs" ops = ["create"]` guards
/// `docs::collection(...).create(...)` through the same before/after machinery
/// as KV — a guarded shape is denied (the doc is never created), an unguarded
/// one is allowed.
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn an_interceptor_guards_docs_create() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let app = common::unique_slug("icd-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();

    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), DOCS_GUARD).unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), DOCS_WRITER).unwrap();
    fs::write(
        dir.path().join("picloud.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"ICD\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nservice = \"docs\"\nops = [\"create\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("picloud.toml"))
        .assert()
        .success();

    // The guarded (secret) create is denied; the public one lands — so exactly
    // one doc exists in the collection.
    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "denied": true, "count": 1 }),
        "the `secret` docs::create must be denied; only the public doc is created"
    );
}

// --- §9.4 M2: ordered before-chain + cycle guard --------------------------

/// A group before-interceptor that denies only `kv::set` of key `"group-key"`.
const GROUP_CHAIN_GUARD: &str = r#"
let op = ctx.request.body;
if op.action == "set" && op.key == "group-key" {
    #{ allowed: false, reason: "group guard" }
} else {
    #{ allowed: true }
}
"#;

/// An app before-interceptor that denies only `kv::set` of key `"app-key"`.
const APP_CHAIN_GUARD: &str = r#"
let op = ctx.request.body;
if op.action == "set" && op.key == "app-key" {
    #{ allowed: false, reason: "app guard" }
} else {
    #{ allowed: true }
}
"#;

/// A writer that probes all three keys: the group-guarded one, the app-guarded
/// one, and a free key. Proves BOTH chain entries run (ancestor→app).
const CHAIN_WRITER: &str = r#"
let g = false;
let a = false;
let free = false;
try { kv::collection("c").set("group-key", 1); } catch(e) { g = true; }
try { kv::collection("c").set("app-key", 1); } catch(e) { a = true; }
try { kv::collection("c").set("free", 1); free = true; } catch(e) {}
#{ group_denied: g, app_denied: a, free_ok: free }
"#;

/// M2: a group AND a descendant app each declare a `(kv, set)` before
/// interceptor. Both run in one write path, ordered ancestor→app: the group's
/// guard denies its key, the app's guard denies its key, and a key neither
/// guards passes — so BOTH chain entries demonstrably execute (a group denial
/// cannot be bypassed by a descendant, and the app adds its own on top).
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn a_before_chain_runs_group_then_app_interceptors_in_order() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let group = common::unique_slug("chain-grp");
    let app = common::unique_slug("chain-app");
    let _g = GroupGuard::new(&env.url, &env.token, &group);
    common::pic_as(&env)
        .args(["groups", "create", &group])
        .assert()
        .success();

    // The group owns its guard + marker.
    let dir = manifest_dir();
    fs::write(
        dir.path().join("scripts/group_guard.rhai"),
        GROUP_CHAIN_GUARD,
    )
    .unwrap();
    fs::write(
        dir.path().join("group.toml"),
        format!(
            "[group]\nslug = \"{group}\"\nname = \"Chain\"\n\n\
             [[scripts]]\nname = \"group_guard\"\nfile = \"scripts/group_guard.rhai\"\n\n\
             [[interceptors]]\nscript = \"group_guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("group.toml"))
        .assert()
        .success();

    // The app under the group owns its OWN guard + marker + writer.
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app, "--group", &group])
        .assert()
        .success();
    fs::write(dir.path().join("scripts/app_guard.rhai"), APP_CHAIN_GUARD).unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), CHAIN_WRITER).unwrap();
    fs::write(
        dir.path().join("app.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"ChainApp\"\n\n\
             [[scripts]]\nname = \"app_guard\"\nfile = \"scripts/app_guard.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\
             [[interceptors]]\nscript = \"app_guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("app.toml"))
        .assert()
        .success();

    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "group_denied": true, "app_denied": true, "free_ok": true }),
        "both the group's and the app's before interceptors must run (ancestor→app)"
    );
}

/// A self-referential interceptor: the `(kv, set)` guard itself performs a
/// `kv::set` (the very op it guards) before allowing. Without a re-entry break
/// that nested write would re-resolve to this same interceptor and recurse
/// forever. The RE-ENTRANCY guard catches it — writes performed BY an
/// interceptor bypass interception — so the audit write lands and the original
/// write proceeds, with no recursion and no deny.
const SELF_REF_GUARD: &str = r#"
kv::collection("audit").set("seen", ctx.request.body.key);
#{ allowed: true }
"#;

/// A writer whose single guarded set triggers the self-referential guard.
const SELF_REF_WRITER: &str = r#"
kv::collection("c").set("x", 1);
#{ done: true }
"#;

/// M2 (cycle safety): a self-referential interceptor completes cleanly rather
/// than recursing. Documented outcome — the RE-ENTRANCY guard is what catches
/// it here (the interceptor's own guarded write bypasses interception, so
/// `run_before` is never re-entered and the identity cycle guard is never
/// reached). The observable result: the writer finishes, both the audit write
/// and the original write persist.
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn a_self_referential_interceptor_does_not_recurse() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let app = common::unique_slug("selfref-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();

    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), SELF_REF_GUARD).unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), SELF_REF_WRITER).unwrap();
    fs::write(
        dir.path().join("picloud.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"SelfRef\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("picloud.toml"))
        .assert()
        .success();

    // No recursion / depth error: the writer completes and returns its map.
    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "done": true }),
        "the self-referential interceptor must complete without recursing"
    );

    // Both writes landed: the interceptor's audit write (bypassed interception)
    // and the original guarded write.
    let seen = String::from_utf8(
        common::pic_as(&env)
            .args(["kv", "get", "--app", &app, "--collection", "audit", "seen"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(
        seen.contains('x'),
        "the interceptor's own write must persist (re-entrancy bypass):\n{seen}"
    );
    let x = String::from_utf8(
        common::pic_as(&env)
            .args(["kv", "get", "--app", &app, "--collection", "c", "x"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(x.contains('1'), "the original write must persist:\n{x}");
}

// --- §9.4 M4: data transform (before) -------------------------------------

/// A before-interceptor that REWRITES the written value via `data` for the key
/// `"doc"` (allow + transform), passing everything else through unchanged.
const TRANSFORM_GUARD: &str = r#"
let op = ctx.request.body;
if op.action == "set" && op.key == "doc" {
    #{ allowed: true, data: #{ redacted: true } }
} else {
    #{ allowed: true }
}
"#;

/// A writer that sets `doc` to a raw value and reads back what was stored.
const TRANSFORM_WRITER: &str = r#"
kv::collection("c").set("doc", #{ secret: "raw" });
kv::collection("c").get("doc")
"#;

/// M4: a before-interceptor that returns `#{ allowed: true, data: ... }` rewrites
/// the value actually written — the store holds the transform, not the original.
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn a_before_interceptor_transforms_the_written_value() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let app = common::unique_slug("xf-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();

    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), TRANSFORM_GUARD).unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), TRANSFORM_WRITER).unwrap();
    fs::write(
        dir.path().join("picloud.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"XF\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("picloud.toml"))
        .assert()
        .success();

    // The writer reads back the STORED value — it must be the transform.
    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "redacted": true }),
        "the stored value must be the interceptor's `data` transform, not the original"
    );
}

// --- §9.4 M3: after-hooks --------------------------------------------------

/// An AFTER-interceptor on `delete` that reads the write's outcome
/// (`op.result`, the was-present bool) and DENIES when a key was actually
/// removed. It cannot roll the delete back (the write already committed) — the
/// deny only surfaces as an error to the caller.
const AFTER_DELETE_GUARD: &str = r#"
let op = ctx.request.body;
if op.action == "delete" && op.result == true {
    #{ allowed: false, reason: "an existing key was deleted" }
} else {
    #{ allowed: true }
}
"#;

/// A writer that seeds a key, deletes it (triggering the after-hook), then
/// checks whether the key survived.
const AFTER_DELETE_WRITER: &str = r#"
kv::collection("c").set("k", 1);
let after_denied = false;
try { kv::collection("c").delete("k"); } catch(e) { after_denied = true; }
let still = kv::collection("c").has("k");
#{ after_denied: after_denied, still: still }
"#;

/// M3: an after-hook runs with the write's `result` in its payload, can DENY
/// (surfacing an error to the caller), but CANNOT roll the write back. The
/// delete's `result` (was-present = true) drives the deny, and the key is gone
/// afterwards despite the error.
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn an_after_hook_sees_the_result_and_cannot_roll_back() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let app = common::unique_slug("after-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();

    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), AFTER_DELETE_GUARD).unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), AFTER_DELETE_WRITER).unwrap();
    fs::write(
        dir.path().join("picloud.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"After\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"delete\"]\nphase = \"after\"\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("picloud.toml"))
        .assert()
        .success();

    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "after_denied": true, "still": false }),
        "the after-hook must see result==true and deny, but the delete must have persisted"
    );
}

// --- §9.4 M5: per-interceptor timeout -------------------------------------

/// A guard that never returns — it must be interrupted by its per-hook timeout
/// rather than hanging the guarded write.
const SLOW_GUARD: &str = r#"
loop {}
"#;

/// A writer whose single guarded set triggers the runaway guard.
const SLOW_WRITER: &str = r#"
let denied = false;
try { kv::collection("c").set("k", 1); } catch(e) { denied = true; }
#{ denied: denied }
"#;

/// M5: a `timeout_ms` on the marker bounds the hook — a runaway `loop {}` guard
/// is interrupted and the op is DENIED (fail closed) within the budget, rather
/// than hanging the write path. The write must not persist.
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn a_runaway_interceptor_is_denied_by_its_timeout() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let app = common::unique_slug("to-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();

    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), SLOW_GUARD).unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), SLOW_WRITER).unwrap();
    fs::write(
        dir.path().join("picloud.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"TO\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\ntimeout_ms = 100\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("picloud.toml"))
        .assert()
        .success();

    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "denied": true }),
        "a runaway interceptor must be timed out and the op denied (fail closed)"
    );

    // The write must not have landed.
    let k = String::from_utf8(
        common::pic_as(&env)
            .args(["kv", "get", "--app", &app, "--collection", "c", "k"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(
        k.trim() == "null" || k.trim() == "()" || k.trim().is_empty(),
        "the timed-out write must NOT persist, got: {k}"
    );
}

// --- §9.4 M12: set_if (CAS) is guarded + `pic interceptors ls` ------------

/// A writer that CAS-writes the guarded key (must be denied) and a free key
/// (must succeed) — proving `set_if` runs the `(kv, set)` guard, not a bypass.
const CAS_WRITER: &str = r#"
let denied = false;
try { kv::collection("c").set_if("secret", (), 1); } catch(e) { denied = true; }
let ok = kv::collection("c").set_if("free", (), 2);
#{ denied: denied, ok: ok }
"#;

/// M12: `set_if` (compare-and-swap) is a write, so it runs the same `(kv, set)`
/// interceptor as `set` — otherwise CAS would be a silent bypass of a set policy.
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn set_if_runs_the_set_interceptor() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let app = common::unique_slug("cas-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();

    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/guard.rhai"), GUARD).unwrap();
    fs::write(dir.path().join("scripts/writer.rhai"), CAS_WRITER).unwrap();
    fs::write(
        dir.path().join("picloud.toml"),
        format!(
            "[app]\nslug = \"{app}\"\nname = \"CAS\"\n\n\
             [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\
             [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\
             [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n"
        ),
    )
    .unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(dir.path().join("picloud.toml"))
        .assert()
        .success();

    let body = invoke_body(&env, &app_script_id(&env, &app, "writer"));
    assert_eq!(
        body,
        serde_json::json!({ "denied": true, "ok": true }),
        "set_if of the guarded key must be denied; a free key must swap"
    );

    // `pic interceptors ls --app` shows the resolved marker.
    let ls = String::from_utf8(
        common::pic_as(&env)
            .args(["interceptors", "ls", "--app", &app])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(
        ls.contains("kv") && ls.contains("set") && ls.contains("guard"),
        "interceptors ls --app must list the kv/set guard:\n{ls}"
    );
}
