//! §11.6 integration test: SHARED-collection triggers.
//! A group-owned `shared = true` trigger watches the group's shared collection.
//! A write to that shared collection (by any subtree app) matches the shared
//! trigger via the OWNING-group match query; a per-app collection of the same
//! name does NOT match it, and the shared trigger does NOT match a per-app
//! write (the `shared` flag is the namespace boundary).
//!
//! Deterministic: drives `list_matching_shared_kv` + `list_matching_kv`
//! directly (no async dispatcher). Skips when `DATABASE_URL` is unset.

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

use picloud_manager_core::trigger_repo::{PostgresTriggerRepo, TriggerRepo};
use picloud_shared::{AppId, GroupId, 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!("shared_triggers: DATABASE_URL unset — skipping");
        return None;
    };
    let pool = PgPoolOptions::new()
        .max_connections(2)
        .connect(&url)
        .await
        .expect("connect");
    sqlx::migrate!("./migrations")
        .run(&pool)
        .await
        .expect("migrate");
    Some(pool)
}

/// Insert a kv trigger (owner + `shared` flag) + its details; returns id.
async fn kv_trigger(
    pool: &PgPool,
    app_id: Option<Uuid>,
    group_id: Option<Uuid>,
    script: Uuid,
    admin: Uuid,
    shared: bool,
    glob: &str,
) -> Uuid {
    let row: (Uuid,) = sqlx::query_as(
        "INSERT INTO triggers \
            (app_id, group_id, script_id, kind, enabled, dispatch_mode, \
             retry_max_attempts, retry_backoff, retry_base_ms, \
             registered_by_principal, name, shared) \
         VALUES ($1, $2, $3, 'kv', TRUE, 'async', 3, 'exponential', 1000, $4, $5, $6) RETURNING id",
    )
    .bind(app_id)
    .bind(group_id)
    .bind(script)
    .bind(admin)
    .bind(Uuid::new_v4().simple().to_string())
    .bind(shared)
    .fetch_one(pool)
    .await
    .expect("trigger");
    sqlx::query(
        "INSERT INTO kv_trigger_details (trigger_id, collection_glob, ops) \
         VALUES ($1, $2, ARRAY['insert'])",
    )
    .bind(row.0)
    .bind(glob)
    .execute(pool)
    .await
    .expect("details");
    row.0
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shared_trigger_matches_only_shared_writes() {
    let Some(pool) = pool_or_skip().await else {
        return;
    };
    let sfx = Uuid::new_v4().simple().to_string();
    let admin = {
        let r: (Uuid,) = sqlx::query_as(
            "INSERT INTO admin_users (username, password_hash) VALUES ($1, 'x') RETURNING id",
        )
        .bind(format!("sh-{sfx}"))
        .fetch_one(&pool)
        .await
        .unwrap();
        r.0
    };
    // Group G with a handler + a SHARED kv trigger on collection "catalog".
    let g: (Uuid,) = sqlx::query_as("INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id")
        .bind(format!("sh-g-{sfx}"))
        .fetch_one(&pool)
        .await
        .unwrap();
    let handler: (Uuid,) = sqlx::query_as(
        "INSERT INTO scripts (name, source, group_id) VALUES ($1, 'x', $2) RETURNING id",
    )
    .bind(format!("on-cat-{sfx}"))
    .bind(g.0)
    .fetch_one(&pool)
    .await
    .unwrap();
    let shared_trig = kv_trigger(&pool, None, Some(g.0), handler.0, admin, true, "catalog").await;

    // App A under G with its OWN (non-shared) kv trigger on "catalog".
    let a: (Uuid,) =
        sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
            .bind(format!("sh-a-{sfx}"))
            .bind(g.0)
            .fetch_one(&pool)
            .await
            .unwrap();
    let app_script: (Uuid,) = sqlx::query_as(
        "INSERT INTO scripts (name, source, app_id) VALUES ($1, 'x', $2) RETURNING id",
    )
    .bind(format!("app-cat-{sfx}"))
    .bind(a.0)
    .fetch_one(&pool)
    .await
    .unwrap();
    let app_trig = kv_trigger(
        &pool,
        Some(a.0),
        None,
        app_script.0,
        admin,
        false,
        "catalog",
    )
    .await;

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

    // A SHARED write to G's "catalog" → matches the shared trigger, NOT the
    // app's per-app trigger.
    let shared_matches = trig
        .list_matching_shared_kv(GroupId::from(g.0), "catalog", KvEventOp::Insert)
        .await
        .expect("shared match");
    assert!(
        shared_matches
            .iter()
            .any(|m| m.trigger_id == shared_trig.into()),
        "a shared write must match the group's shared trigger"
    );
    assert!(
        !shared_matches
            .iter()
            .any(|m| m.trigger_id == app_trig.into()),
        "a shared write must NOT match a per-app trigger of the same name"
    );

    // A PER-APP write to app A's "catalog" → matches the app's trigger, NOT the
    // shared trigger (the per-app query excludes `shared = TRUE`).
    let app_matches = trig
        .list_matching_kv(AppId::from(a.0), "catalog", KvEventOp::Insert)
        .await
        .expect("app match");
    assert!(
        app_matches.iter().any(|m| m.trigger_id == app_trig.into()),
        "a per-app write must match the app's own trigger"
    );
    assert!(
        !app_matches
            .iter()
            .any(|m| m.trigger_id == shared_trig.into()),
        "a per-app write must NOT match the group's shared trigger"
    );

    // Cleanup.
    let _ = sqlx::query("DELETE FROM triggers WHERE id = ANY($1)")
        .bind(vec![shared_trig, app_trig])
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM apps WHERE id = $1")
        .bind(a.0)
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM scripts WHERE id = ANY($1)")
        .bind(vec![handler.0, app_script.0])
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM groups WHERE id = $1")
        .bind(g.0)
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM admin_users WHERE id = $1")
        .bind(admin)
        .execute(&pool)
        .await;
}
