//! §11.6 — shared-collection triggers, declarative authoring end to end via
//! `pic`. A group declares a shared kv collection + a `[[triggers.kv]]
//! shared = true` handler watching it; the template applies, `pic triggers ls
//! --group` shows `shared = true`; a shared trigger on an UNDECLARED collection
//! is rejected, and `shared = true` on an app trigger is rejected.
//!
//! The live FIRING (a shared write matches the shared trigger, a per-app write
//! does not) is pinned deterministically by
//! `manager-core/tests/shared_triggers.rs` — driving the async dispatcher from a
//! journey is deliberately avoided (codebase norm).

use std::fs;

use tempfile::TempDir;

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

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

fn group_script_id(env: &common::TestEnv, group: &str, name: &str) -> String {
    let ls = common::pic_as(env)
        .args(["scripts", "ls", "--group", group])
        .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!("group script `{name}` not found:\n{table}"))
}

#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn shared_kv_trigger_applies_lists_and_validates() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let group = common::unique_slug("shtrig-grp");

    let _g = GroupGuard::new(&env.url, &env.token, &group);
    common::pic_as(&env)
        .args(["groups", "create", &group])
        .assert()
        .success();

    // Group handler for the shared collection.
    let dir = manifest_dir();
    fs::write(
        dir.path().join("scripts/on-cat.rhai"),
        r#"log::info("shared catalog write"); "ok""#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/on-cat.rhai"))
        .args(["--group", &group, "--name", "on-cat"])
        .assert()
        .success();
    let _gs = ScriptGuard::new(
        &env.url,
        &env.token,
        &group_script_id(&env, &group, "on-cat"),
    );

    // Group declares a shared kv collection `catalog` + a shared kv trigger.
    let gmanifest = format!(
        "[group]\nslug = \"{group}\"\nname = \"ShTrigG\"\n\
         collections = [{{ name = \"catalog\", kind = \"kv\" }}]\n\n\
         [[triggers.kv]]\nscript = \"on-cat\"\ncollection_glob = \"catalog\"\nshared = true\n"
    );
    let gpath = dir.path().join("group.toml");
    fs::write(&gpath, &gmanifest).unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&gpath)
        .assert()
        .success();

    // `pic triggers ls --group` shows shared = true for the kv trigger.
    let ls = String::from_utf8(
        common::pic_as(&env)
            .args(["triggers", "ls", "--group", &group])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    let row = ls
        .lines()
        .map(common::cells)
        .find(|c| c.contains(&"on-cat"))
        .unwrap_or_else(|| panic!("no on-cat trigger row:\n{ls}"));
    assert!(
        row.contains(&"true"),
        "the shared column must read true for the shared trigger:\n{ls}"
    );

    // A shared trigger on a collection the group does NOT declare shared is
    // rejected at apply.
    let bad_group = format!(
        "[group]\nslug = \"{group}\"\nname = \"ShTrigG\"\n\
         collections = [{{ name = \"catalog\", kind = \"kv\" }}]\n\n\
         [[triggers.kv]]\nscript = \"on-cat\"\ncollection_glob = \"undeclared\"\nshared = true\n"
    );
    fs::write(&gpath, &bad_group).unwrap();
    let out = common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&gpath)
        .output()
        .expect("apply bad");
    assert!(
        !out.status.success(),
        "a shared trigger on an undeclared collection must be rejected"
    );

    // `shared = true` on an APP trigger is rejected.
    let app = common::unique_slug("shtrig-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();
    fs::write(
        dir.path().join("scripts/app-h.rhai"),
        r#"log::info("app"); "ok""#,
    )
    .unwrap();
    let amanifest = format!(
        "[app]\nslug = \"{app}\"\nname = \"App\"\n\n\
         [[scripts]]\nname = \"app-h\"\nfile = \"scripts/app-h.rhai\"\n\n\
         [[triggers.kv]]\nscript = \"app-h\"\ncollection_glob = \"widgets\"\nshared = true\n"
    );
    let apath = dir.path().join("app.toml");
    fs::write(&apath, &amanifest).unwrap();
    let out = common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&apath)
        .output()
        .expect("apply app");
    assert!(
        !out.status.success(),
        "a shared trigger on an app is rejected (apps don't own shared collections)"
    );
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.to_lowercase().contains("shared"),
        "the rejection must mention shared:\n{err}"
    );
}
