//! §11 tail integration test: the live expansion of group ROUTE templates into
//! per-app match slices. A group-owned route TEMPLATE must land in the compiled
//! slice of a **descendant** app and must NOT land in an app in a **sibling**
//! subtree — the ancestor-chain expansion is the isolation boundary. An app's
//! own route with an identical binding must **shadow** the template (nearest
//! owner wins); a non-identical app route must **coexist**.
//!
//! Deterministic: drives `list_effective` + `compile_effective_routes` directly
//! (no async dispatcher), pinning the security-critical SQL + the shadow rule
//! 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::route_admin::compile_effective_routes;
use picloud_manager_core::route_repo::{PostgresRouteRepository, RouteRepository};
use picloud_shared::AppId;
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_route_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
}

async fn app_under(pool: &PgPool, slug: &str, group: Uuid) -> Uuid {
    let row: (Uuid,) =
        sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
            .bind(slug)
            .bind(group)
            .fetch_one(pool)
            .await
            .expect("app insert");
    row.0
}

/// The compiled match slice for `app` — its own routes plus inherited
/// ancestor-group templates, after nearest-wins shadowing.
async fn slice_paths(repo: &PostgresRouteRepository, app: Uuid) -> Vec<(String, Uuid)> {
    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()
        .filter(|c| c.app_id == AppId::from(app))
        .map(|c| {
            // PathPattern's Debug carries the raw path; pair it with the bound
            // script so the shadow assertion can check which handler won.
            (format!("{:?}", c.path), c.script_id.into_inner())
        })
        .collect()
}

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

    // 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!("grt-g-{sfx}"),
    )
    .await;
    let g2 = id1(
        &pool,
        "INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id",
        &format!("grt-g2-{sfx}"),
    )
    .await;

    // App A under G (descendant); app C under G2 (sibling subtree).
    let a = app_under(&pool, &format!("grt-a-{sfx}"), g).await;
    let c = app_under(&pool, &format!("grt-c-{sfx}"), g2).await;

    // Group-owned handler script + a group route TEMPLATE binding it.
    let group_script: (Uuid,) = sqlx::query_as(
        "INSERT INTO scripts (name, source, group_id) VALUES ($1, 'x', $2) RETURNING id",
    )
    .bind(format!("ghandler-{sfx}"))
    .bind(g)
    .fetch_one(&pool)
    .await
    .expect("group script");
    sqlx::query(
        "INSERT INTO routes (group_id, script_id, host_kind, host, path_kind, path, method) \
         VALUES ($1, $2, 'any', '', 'exact', '/hello', NULL)",
    )
    .bind(g)
    .bind(group_script.0)
    .execute(&pool)
    .await
    .expect("group route template");

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

    // Descendant app A's slice CONTAINS the template, bound to the group script.
    let a_slice = slice_paths(&repo, a).await;
    assert!(
        a_slice
            .iter()
            .any(|(p, sid)| p.contains("/hello") && *sid == group_script.0),
        "a descendant app must inherit the group route template:\n{a_slice:?}"
    );

    // Sibling-subtree app C's slice does NOT — the chain expansion is the bound.
    let c_slice = slice_paths(&repo, c).await;
    assert!(
        !c_slice.iter().any(|(p, _)| p.contains("/hello")),
        "a sibling-subtree app must NOT inherit another subtree's template:\n{c_slice:?}"
    );

    // A's OWN /hello route (its own app-owned script) must SHADOW the template:
    // exactly one compiled /hello for A, bound to the app script, not the group.
    let app_script: (Uuid,) = sqlx::query_as(
        "INSERT INTO scripts (name, source, app_id) VALUES ($1, 'x', $2) RETURNING id",
    )
    .bind(format!("ahandler-{sfx}"))
    .bind(a)
    .fetch_one(&pool)
    .await
    .expect("app script");
    sqlx::query(
        "INSERT INTO routes (app_id, script_id, host_kind, host, path_kind, path, method) \
         VALUES ($1, $2, 'any', '', 'exact', '/hello', NULL)",
    )
    .bind(a)
    .bind(app_script.0)
    .execute(&pool)
    .await
    .expect("app route shadow");

    let a_after = slice_paths(&repo, a).await;
    let hellos: Vec<_> = a_after
        .iter()
        .filter(|(p, _)| p.contains("/hello"))
        .collect();
    assert_eq!(
        hellos.len(),
        1,
        "nearest-wins shadowing must leave exactly one /hello for A:\n{a_after:?}"
    );
    assert_eq!(
        hellos[0].1, app_script.0,
        "the app's own route must win over the inherited group template"
    );

    // A non-identical app route (different path) must COEXIST with the template.
    sqlx::query(
        "INSERT INTO routes (app_id, script_id, host_kind, host, path_kind, path, method) \
         VALUES ($1, $2, 'any', '', 'exact', '/own', NULL)",
    )
    .bind(a)
    .bind(app_script.0)
    .execute(&pool)
    .await
    .expect("app route coexist");
    let a_final = slice_paths(&repo, a).await;
    assert!(
        a_final.iter().any(|(p, _)| p.contains("/own")),
        "a non-identical app route must coexist with the inherited template:\n{a_final:?}"
    );

    // Cleanup (FK order: routes → scripts → apps → groups).
    let _ = sqlx::query("DELETE FROM routes WHERE app_id = ANY($1) OR group_id = $2")
        .bind(vec![a, c])
        .bind(g)
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM scripts WHERE id = ANY($1)")
        .bind(vec![group_script.0, app_script.0])
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM apps WHERE id = ANY($1)")
        .bind(vec![a, c])
        .execute(&pool)
        .await;
    let _ = sqlx::query("DELETE FROM groups WHERE id = ANY($1)")
        .bind(vec![g, g2])
        .execute(&pool)
        .await;
}
