//! §11 tail integration test: the live chain-union dispatch for group trigger
//! templates. A group-owned kv trigger TEMPLATE must be matched for a
//! **descendant** app (the union via `CHAIN_LEVELS_CTE`) and must NOT be matched
//! for an app in a **sibling** subtree — that walk is the isolation boundary.
//!
//! Deterministic (no async dispatcher) so it pins the security-critical SQL
//! without flakiness. Skips cleanly when `DATABASE_URL` is unset.

#![allow(
    clippy::needless_pass_by_value,
    clippy::many_single_char_names,
    clippy::too_many_lines
)]

use picloud_manager_core::trigger_repo::{PostgresTriggerRepo, TriggerRepo};
use picloud_shared::{AppId, KvEventOp};
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use uuid::Uuid;

async fn pool_or_skip() -> Option<PgPool> {
    let Ok(url) = std::env::var("DATABASE_URL") else {
        eprintln!("group_trigger_templates: DATABASE_URL unset — skipping");
        return None;
    };
    let pool = PgPoolOptions::new()
        .max_connections(2)
        .connect(&url)
        .await
        .expect("connect to DATABASE_URL");
    sqlx::migrate!("./migrations")
        .run(&pool)
        .await
        .expect("apply migrations");
    Some(pool)
}

async fn id1(pool: &PgPool, sql: &str, bind: &str) -> Uuid {
    let row: (Uuid,) = sqlx::query_as(sql)
        .bind(bind)
        .fetch_one(pool)
        .await
        .expect("insert returning id");
    row.0
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn group_kv_template_matches_descendant_not_sibling() {
    let Some(pool) = pool_or_skip().await else {
        return;
    };
    let sfx = Uuid::new_v4().simple().to_string();

    // registered_by principal
    let admin = id1(
        &pool,
        "INSERT INTO admin_users (username, password_hash) VALUES ($1, 'x') RETURNING id",
        &format!("gtt-{sfx}"),
    )
    .await;

    // G owns the template; G2 is an unrelated sibling subtree.
    let g = id1(
        &pool,
        "INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id",
        &format!("gtt-g-{sfx}"),
    )
    .await;
    let g2 = id1(
        &pool,
        "INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id",
        &format!("gtt-g2-{sfx}"),
    )
    .await;

    // App A under G (descendant); app C under G2 (sibling subtree).
    let a: (Uuid,) =
        sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
            .bind(format!("gtt-a-{sfx}"))
            .bind(g)
            .fetch_one(&pool)
            .await
            .expect("app A");
    let c: (Uuid,) =
        sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
            .bind(format!("gtt-c-{sfx}"))
            .bind(g2)
            .fetch_one(&pool)
            .await
            .expect("app C");

    // Group-owned handler script under G.
    let s: (Uuid,) = sqlx::query_as(
        "INSERT INTO scripts (name, source, group_id) VALUES ($1, 'x', $2) RETURNING id",
    )
    .bind(format!("handler-{sfx}"))
    .bind(g)
    .fetch_one(&pool)
    .await
    .expect("group script");

    // Group kv trigger TEMPLATE (group_id = G, app_id NULL) + details.
    let t: (Uuid,) = sqlx::query_as(
        "INSERT INTO triggers \
            (group_id, script_id, kind, enabled, dispatch_mode, \
             retry_max_attempts, retry_backoff, retry_base_ms, \
             registered_by_principal, name) \
         VALUES ($1, $2, 'kv', TRUE, 'async', 3, 'exponential', 1000, $3, $4) \
         RETURNING id",
    )
    .bind(g)
    .bind(s.0)
    .bind(admin)
    .bind(format!("tmpl-{sfx}"))
    .fetch_one(&pool)
    .await
    .expect("template trigger");
    sqlx::query(
        "INSERT INTO kv_trigger_details (trigger_id, collection_glob, ops) \
         VALUES ($1, '*', ARRAY['insert'])",
    )
    .bind(t.0)
    .execute(&pool)
    .await
    .expect("kv details");

    let repo = PostgresTriggerRepo::new(pool.clone());

    // Descendant app A's kv insert matches the ancestor group's template.
    let matched = repo
        .list_matching_kv(AppId::from(a.0), "users", KvEventOp::Insert)
        .await
        .expect("match for A");
    assert!(
        matched.iter().any(|m| m.trigger_id == t.0.into()),
        "a descendant app must match the group's kv template"
    );

    // Sibling-subtree app C must NOT — the chain union is the isolation boundary.
    let none = repo
        .list_matching_kv(AppId::from(c.0), "users", KvEventOp::Insert)
        .await
        .expect("match for C");
    assert!(
        !none.iter().any(|m| m.trigger_id == t.0.into()),
        "a sibling-subtree app must NOT match another subtree's group template"
    );

    // Cleanup (best-effort; ordering respects the FKs).
    let _ = sqlx::query("DELETE FROM triggers WHERE id = $1")
        .bind(t.0)
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM scripts WHERE id = $1")
        .bind(s.0)
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM apps WHERE id = ANY($1)")
        .bind(vec![a.0, c.0])
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM groups WHERE id = ANY($1)")
        .bind(vec![g, g2])
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM admin_users WHERE id = $1")
        .bind(admin)
        .execute(&pool)
        .await;
}
