//! §11 tail integration test: `sealed` (non-suppressible) group templates.
//! A group marks a TRIGGER and a ROUTE template `sealed = true`; a descendant
//! app that declares a `[suppress]` for both references STILL fires the trigger
//! (dispatch anti-join skips a sealed row) and STILL serves the route
//! (rebuild-time skip is gated on `!sealed`). The gate is exactly `sealed`: an
//! UNSEALED sibling template with the same suppression is still declined.
//!
//! Deterministic: drives `list_matching_kv` + `list_effective` /
//! `compile_effective_routes` directly (no async dispatcher). 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::route_admin::compile_effective_routes;
use picloud_manager_core::route_repo::{PostgresRouteRepository, RouteRepository};
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!("sealed_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
}

/// A group-owned script handler.
async fn group_handler(pool: &PgPool, name: &str, group: Uuid) -> Uuid {
    let row: (Uuid,) = sqlx::query_as(
        "INSERT INTO scripts (name, source, group_id) VALUES ($1, 'x', $2) RETURNING id",
    )
    .bind(name)
    .bind(group)
    .fetch_one(pool)
    .await
    .expect("group handler");
    row.0
}

/// A group-owned kv trigger TEMPLATE (glob `*`, op insert), with `sealed`.
async fn kv_template(pool: &PgPool, group: Uuid, script: Uuid, admin: Uuid, sealed: bool) -> Uuid {
    let row: (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, sealed) \
         VALUES ($1, $2, 'kv', TRUE, 'async', 3, 'exponential', 1000, $3, $4, $5) RETURNING id",
    )
    .bind(group)
    .bind(script)
    .bind(admin)
    .bind(Uuid::new_v4().simple().to_string())
    .bind(sealed)
    .fetch_one(pool)
    .await
    .expect("kv template");
    sqlx::query(
        "INSERT INTO kv_trigger_details (trigger_id, collection_glob, ops) \
         VALUES ($1, '*', ARRAY['insert'])",
    )
    .bind(row.0)
    .execute(pool)
    .await
    .expect("kv details");
    row.0
}

/// A group-owned route TEMPLATE at `path`, with `sealed`.
async fn route_template(pool: &PgPool, group: Uuid, script: Uuid, path: &str, sealed: bool) {
    sqlx::query(
        "INSERT INTO routes \
            (group_id, script_id, host_kind, host, path_kind, path, method, sealed) \
         VALUES ($1, $2, 'any', '', 'exact', $3, NULL, $4)",
    )
    .bind(group)
    .bind(script)
    .bind(path)
    .bind(sealed)
    .execute(pool)
    .await
    .expect("route template");
}

/// Whether `app`'s compiled route slice serves `path`.
async fn serves(repo: &PostgresRouteRepository, app: Uuid, path: &str) -> bool {
    let effective = repo.list_effective().await.expect("list_effective");
    let mut suppressed: std::collections::HashMap<(AppId, String), i32> =
        std::collections::HashMap::new();
    for (a, p, d) in repo
        .list_route_suppressions()
        .await
        .expect("list_route_suppressions")
    {
        suppressed
            .entry((a, p))
            .and_modify(|x| *x = (*x).min(d))
            .or_insert(d);
    }
    compile_effective_routes(&effective, &suppressed)
        .into_iter()
        .any(|c| c.app_id == AppId::from(app) && format!("{:?}", c.path).contains(path))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sealed_template_survives_suppression_unsealed_still_declined() {
    let Some(pool) = pool_or_skip().await else {
        return;
    };
    let sfx = Uuid::new_v4().simple().to_string();
    let admin = id1(
        &pool,
        "INSERT INTO admin_users (username, password_hash) VALUES ($1, 'x') RETURNING id",
        &format!("seal-{sfx}"),
    )
    .await;

    // Group G owns two handlers, each with a trigger + a route template:
    //   `audit` → SEALED (non-suppressible)
    //   `plain` → unsealed (suppressible, the control)
    let g = id1(
        &pool,
        "INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id",
        &format!("seal-g-{sfx}"),
    )
    .await;
    let audit_name = format!("audit-{sfx}");
    let plain_name = format!("plain-{sfx}");
    let audit = group_handler(&pool, &audit_name, g).await;
    let plain = group_handler(&pool, &plain_name, g).await;

    let sealed_trig = kv_template(&pool, g, audit, admin, true).await;
    let plain_trig = kv_template(&pool, g, plain, admin, false).await;
    route_template(&pool, g, audit, "/sealed", true).await;
    route_template(&pool, g, plain, "/plain", false).await;

    // App A suppresses BOTH handlers + BOTH paths.
    let a: (Uuid,) =
        sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
            .bind(format!("seal-a-{sfx}"))
            .bind(g)
            .fetch_one(&pool)
            .await
            .expect("app A");
    let a = a.0;
    sqlx::query(
        "INSERT INTO template_suppressions (app_id, target_kind, reference) VALUES \
            ($1, 'trigger', $2), ($1, 'trigger', $3), \
            ($1, 'route', '/sealed'), ($1, 'route', '/plain')",
    )
    .bind(a)
    .bind(&audit_name)
    .bind(&plain_name)
    .execute(&pool)
    .await
    .expect("suppressions for A");

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

    let matched = trig
        .list_matching_kv(AppId::from(a), "users", KvEventOp::Insert)
        .await
        .expect("match A");

    // Sealed template: suppression is IGNORED — the trigger still fires and the
    // route still serves.
    assert!(
        matched.iter().any(|m| m.trigger_id == sealed_trig.into()),
        "a SEALED trigger template fires despite the suppression"
    );
    assert!(
        serves(&routes, a, "/sealed").await,
        "a SEALED route template serves despite the suppression"
    );

    // Unsealed control: the same suppression DOES decline it — proving the gate
    // is exactly `sealed`, not a blanket bypass.
    assert!(
        !matched.iter().any(|m| m.trigger_id == plain_trig.into()),
        "an UNSEALED trigger template is still declined by the suppression"
    );
    assert!(
        !serves(&routes, a, "/plain").await,
        "an UNSEALED route template is still declined by the suppression"
    );

    // Cleanup (FK order).
    let _ = sqlx::query("DELETE FROM triggers WHERE id = ANY($1)")
        .bind(vec![sealed_trig, plain_trig])
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM routes WHERE group_id = $1")
        .bind(g)
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM template_suppressions WHERE app_id = $1")
        .bind(a)
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM scripts WHERE id = ANY($1)")
        .bind(vec![audit, plain])
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM apps WHERE id = $1")
        .bind(a)
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM groups WHERE id = $1")
        .bind(g)
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM admin_users WHERE id = $1")
        .bind(admin)
        .execute(&pool)
        .await;
}
