//! CRUD over the `routes` table.
//!
//! The orchestrator's `AppRouteTables` is repopulated from this repo
//! after every write — see the route_admin module for the binding.

use async_trait::async_trait;
use picloud_shared::{
    AppId, DispatchMode, GroupId, HostKind, PathKind, Route, ScriptId, ScriptOwner,
};
use sqlx::PgPool;
use uuid::Uuid;

use crate::repo::ScriptRepositoryError;

#[derive(Debug, Clone)]
pub struct NewRoute {
    /// §11 tail: an **app** owns a concrete route; a **group** owns a route
    /// TEMPLATE. The interactive route API always passes `App`; the declarative
    /// reconcile passes the bundle node's owner.
    pub owner: ScriptOwner,
    pub script_id: ScriptId,
    pub host_kind: HostKind,
    pub host: String,
    pub host_param_name: Option<String>,
    pub path_kind: PathKind,
    pub path: String,
    pub method: Option<String>,
    pub dispatch_mode: DispatchMode,
    /// Three-state lifecycle (§4.3). Create active by default.
    pub enabled: bool,
    /// §11 tail: `true` for a sealed (non-suppressible) group route template.
    /// Always `false` for an app-owned route (the reconcile rejects sealed on
    /// an app owner before reaching here).
    pub sealed: bool,
}

/// A route resolved for a specific app via the §11 tail expansion: the route
/// row itself plus the **effective app** it applies to (the firing
/// descendant) and the chain `depth` at which its owner sits (0 = the app's
/// own route, ≥1 = an ancestor-group template). Used only by the in-memory
/// RouteTable rebuild — never on the request hot path.
#[derive(Debug, Clone)]
pub struct EffectiveRoute {
    pub effective_app_id: AppId,
    pub depth: i32,
    pub route: Route,
}

#[async_trait]
pub trait RouteRepository: Send + Sync {
    async fn list_all(&self) -> Result<Vec<Route>, ScriptRepositoryError>;
    /// Single-row lookup. Used by `DELETE /api/v1/admin/routes/{id}` so
    /// the capability check binds to the route's actual `app_id`
    /// (not a path param).
    async fn get(&self, route_id: Uuid) -> Result<Option<Route>, ScriptRepositoryError>;
    async fn list_for_app(&self, app_id: AppId) -> Result<Vec<Route>, ScriptRepositoryError>;
    /// Group-owned route TEMPLATES (§11 tail) declared directly at `group_id`.
    /// Backs the declarative apply diff for a `[group]` node and
    /// `pic routes ls --group`. Defaults to empty so non-Postgres impls
    /// (tests) need not provide it.
    async fn list_for_group(
        &self,
        _group_id: GroupId,
    ) -> Result<Vec<Route>, ScriptRepositoryError> {
        Ok(Vec::new())
    }
    /// §11 tail per-app opt-out: all ROUTE suppressions as
    /// `(effective_app_id, path, suppressor_depth)` — the depth is the chain
    /// distance from the app to the owner that DECLARED the suppression (0 for
    /// the app's own suppression, >0 for an ancestor group's). The route-table
    /// rebuild drops an inherited route at a suppressed path only when the
    /// route's owner is ABOVE the suppressor (`route_depth > suppressor_depth`),
    /// so a nearer descendant's own re-declaration is never over-declined.
    /// Defaults empty (non-Postgres impls have no suppressions).
    async fn list_route_suppressions(
        &self,
    ) -> Result<Vec<(AppId, String, i32)>, ScriptRepositoryError> {
        Ok(Vec::new())
    }
    /// §11 tail: every route resolved for every app — each app's own routes
    /// PLUS its ancestor-group templates, tagged with the effective app and
    /// the owner's chain depth. The in-memory RouteTable rebuild consumes this
    /// (expansion happens here, once per rebuild, never per request). Defaults
    /// to `list_all` mapped at depth 0 so non-Postgres impls degrade to the
    /// pre-§11 (app-only) behavior.
    async fn list_effective(&self) -> Result<Vec<EffectiveRoute>, ScriptRepositoryError> {
        Ok(self
            .list_all()
            .await?
            .into_iter()
            .filter_map(|route| {
                route.app_id.map(|a| EffectiveRoute {
                    effective_app_id: a,
                    depth: 0,
                    route,
                })
            })
            .collect())
    }
    async fn list_for_script(
        &self,
        script_id: ScriptId,
    ) -> Result<Vec<Route>, ScriptRepositoryError>;
    async fn create(&self, input: NewRoute) -> Result<Route, ScriptRepositoryError>;
    async fn delete(&self, route_id: Uuid) -> Result<(), ScriptRepositoryError>;
    /// Count routes whose host_kind/host pair matches a pattern in
    /// `app_id`. Used by the domain-claim delete guard.
    async fn count_for_app_host(
        &self,
        app_id: AppId,
        host_kind: HostKind,
        host: &str,
    ) -> Result<i64, ScriptRepositoryError>;
}

pub struct PostgresRouteRepository {
    pool: PgPool,
}

impl PostgresRouteRepository {
    #[must_use]
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

#[async_trait]
impl RouteRepository for PostgresRouteRepository {
    async fn list_all(&self) -> Result<Vec<Route>, ScriptRepositoryError> {
        let rows = sqlx::query_as::<_, RouteRow>(
            "SELECT id, app_id, group_id, script_id, host_kind, host, host_param_name, \
                    path_kind, path, method, dispatch_mode, enabled, created_at \
             FROM routes ORDER BY created_at",
        )
        .fetch_all(&self.pool)
        .await?;
        Ok(rows.into_iter().map(Into::into).collect())
    }

    async fn get(&self, route_id: Uuid) -> Result<Option<Route>, ScriptRepositoryError> {
        let row = sqlx::query_as::<_, RouteRow>(
            "SELECT id, app_id, group_id, script_id, host_kind, host, host_param_name, \
                    path_kind, path, method, dispatch_mode, enabled, created_at \
             FROM routes WHERE id = $1",
        )
        .bind(route_id)
        .fetch_optional(&self.pool)
        .await?;
        Ok(row.map(Into::into))
    }

    async fn list_for_app(&self, app_id: AppId) -> Result<Vec<Route>, ScriptRepositoryError> {
        let rows = sqlx::query_as::<_, RouteRow>(
            "SELECT id, app_id, group_id, script_id, host_kind, host, host_param_name, \
                    path_kind, path, method, dispatch_mode, enabled, created_at \
             FROM routes WHERE app_id = $1 ORDER BY created_at",
        )
        .bind(app_id.into_inner())
        .fetch_all(&self.pool)
        .await?;
        Ok(rows.into_iter().map(Into::into).collect())
    }

    async fn list_for_group(&self, group_id: GroupId) -> Result<Vec<Route>, ScriptRepositoryError> {
        let rows = sqlx::query_as::<_, RouteRow>(
            "SELECT id, app_id, group_id, script_id, host_kind, host, host_param_name, \
                    path_kind, path, method, dispatch_mode, enabled, sealed, created_at \
             FROM routes WHERE group_id = $1 ORDER BY created_at",
        )
        .bind(group_id.into_inner())
        .fetch_all(&self.pool)
        .await?;
        Ok(rows.into_iter().map(Into::into).collect())
    }

    async fn list_route_suppressions(
        &self,
    ) -> Result<Vec<(AppId, String, i32)>, ScriptRepositoryError> {
        // §11 tail M1: a route suppression is owned by an app (declines for
        // itself) OR a group (declines for its whole subtree). Expand each
        // group-owned suppression across every descendant app via the all-apps
        // `app_chain` CTE (the same one `list_effective` uses). We also return
        // `ac.depth` — the chain distance from the effective app to the owner
        // that DECLARED the suppression — so the rebuild only declines routes
        // inherited from ABOVE that owner (`route_depth > suppressor_depth`),
        // not a nearer descendant's own re-declaration at the same path.
        let rows: Vec<(Uuid, String, i32)> = sqlx::query_as(
            "WITH RECURSIVE app_chain AS ( \
                 SELECT a.id AS effective_app_id, a.id AS owner_app, \
                        NULL::uuid AS owner_group, a.group_id AS next_group, 0 AS depth \
                 FROM apps a \
               UNION ALL \
                 SELECT ac.effective_app_id, NULL::uuid, g.id, g.parent_id, ac.depth + 1 \
                 FROM groups g JOIN app_chain ac ON g.id = ac.next_group \
                 WHERE ac.depth < 64 \
             ) \
             SELECT ac.effective_app_id, ts.reference, ac.depth \
             FROM app_chain ac \
             JOIN template_suppressions ts \
               ON (ts.app_id = ac.owner_app OR ts.group_id = ac.owner_group) \
             WHERE ts.target_kind = 'route'",
        )
        .fetch_all(&self.pool)
        .await?;
        Ok(rows.into_iter().map(|(a, r, d)| (a.into(), r, d)).collect())
    }

    async fn list_effective(&self) -> Result<Vec<EffectiveRoute>, ScriptRepositoryError> {
        // The all-apps generalization of CHAIN_LEVELS_CTE: for EVERY app, walk
        // its ancestor-group chain, then join routes owned at each level. A
        // group template appears once per descendant app (tagged with that
        // app + the owner's depth); an app's own route appears at depth 0.
        // Runs only on a RouteTable rebuild, never per request.
        let rows = sqlx::query_as::<_, EffectiveRouteRow>(
            "WITH RECURSIVE app_chain AS ( \
                 SELECT a.id AS effective_app_id, a.id AS owner_app, \
                        NULL::uuid AS owner_group, a.group_id AS next_group, 0 AS depth \
                 FROM apps a \
               UNION ALL \
                 SELECT ac.effective_app_id, NULL::uuid, g.id, g.parent_id, ac.depth + 1 \
                 FROM groups g JOIN app_chain ac ON g.id = ac.next_group \
                 WHERE ac.depth < 64 \
             ) \
             SELECT ac.effective_app_id, ac.depth, \
                    r.id, r.app_id, r.group_id, r.script_id, r.host_kind, r.host, \
                    r.host_param_name, r.path_kind, r.path, r.method, \
                    r.dispatch_mode, r.enabled, r.sealed, r.created_at \
             FROM app_chain ac \
             JOIN routes r ON (r.app_id = ac.owner_app OR r.group_id = ac.owner_group) \
             ORDER BY ac.effective_app_id, ac.depth",
        )
        .fetch_all(&self.pool)
        .await?;
        Ok(rows
            .into_iter()
            .map(|er| EffectiveRoute {
                effective_app_id: er.effective_app_id.into(),
                depth: er.depth,
                route: er.row.into(),
            })
            .collect())
    }

    async fn list_for_script(
        &self,
        script_id: ScriptId,
    ) -> Result<Vec<Route>, ScriptRepositoryError> {
        let rows = sqlx::query_as::<_, RouteRow>(
            "SELECT id, app_id, group_id, script_id, host_kind, host, host_param_name, \
                    path_kind, path, method, dispatch_mode, enabled, created_at \
             FROM routes WHERE script_id = $1 ORDER BY created_at",
        )
        .bind(script_id.into_inner())
        .fetch_all(&self.pool)
        .await?;
        Ok(rows.into_iter().map(Into::into).collect())
    }

    async fn create(&self, input: NewRoute) -> Result<Route, ScriptRepositoryError> {
        let mut tx = self.pool.begin().await?;
        let route = insert_route_tx(&mut tx, &input).await?;
        tx.commit().await?;
        Ok(route)
    }

    async fn delete(&self, route_id: Uuid) -> Result<(), ScriptRepositoryError> {
        let res = sqlx::query("DELETE FROM routes WHERE id = $1")
            .bind(route_id)
            .execute(&self.pool)
            .await?;
        if res.rows_affected() == 0 {
            return Err(ScriptRepositoryError::NotFound(ScriptId::from(route_id)));
        }
        Ok(())
    }

    async fn count_for_app_host(
        &self,
        app_id: AppId,
        host_kind: HostKind,
        host: &str,
    ) -> Result<i64, ScriptRepositoryError> {
        let count: (i64,) = sqlx::query_as(
            "SELECT COUNT(*) FROM routes \
             WHERE app_id = $1 AND host_kind = $2 AND host = $3",
        )
        .bind(app_id.into_inner())
        .bind(host_kind_str(host_kind))
        .bind(host)
        .fetch_one(&self.pool)
        .await?;
        Ok(count.0)
    }
}

const fn host_kind_str(k: HostKind) -> &'static str {
    match k {
        HostKind::Any => "any",
        HostKind::Strict => "strict",
        HostKind::Wildcard => "wildcard",
    }
}

const fn path_kind_str(k: PathKind) -> &'static str {
    match k {
        PathKind::Exact => "exact",
        PathKind::Prefix => "prefix",
        PathKind::Param => "param",
    }
}

/// Insert a route within an existing transaction (declarative apply
/// composes scripts + routes + triggers into one tx). Mirrors `create`
/// minus the `begin`/`commit`.
pub(crate) async fn insert_route_tx(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    input: &NewRoute,
) -> Result<Route, ScriptRepositoryError> {
    // §11 tail: an app owns a concrete route, a group owns a template.
    let (owner_app_id, owner_group_id) = match input.owner {
        ScriptOwner::App(a) => (Some(a.into_inner()), None),
        ScriptOwner::Group(g) => (None, Some(g.into_inner())),
    };
    let res = sqlx::query_as::<_, RouteRow>(
        "INSERT INTO routes ( \
            app_id, group_id, script_id, host_kind, host, host_param_name, \
            path_kind, path, method, dispatch_mode, enabled, sealed \
         ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) \
         RETURNING id, app_id, group_id, script_id, host_kind, host, host_param_name, \
                   path_kind, path, method, dispatch_mode, enabled, sealed, created_at",
    )
    .bind(owner_app_id)
    .bind(owner_group_id)
    .bind(input.script_id.into_inner())
    .bind(host_kind_str(input.host_kind))
    .bind(&input.host)
    .bind(input.host_param_name.as_deref())
    .bind(path_kind_str(input.path_kind))
    .bind(&input.path)
    .bind(input.method.as_deref())
    .bind(input.dispatch_mode.as_str())
    .bind(input.enabled)
    .bind(input.sealed)
    .fetch_one(&mut **tx)
    .await;
    match res {
        Ok(row) => Ok(row.into()),
        Err(sqlx::Error::Database(e)) if e.is_unique_violation() => Err(
            ScriptRepositoryError::Conflict("a route with this binding already exists".into()),
        ),
        Err(sqlx::Error::Database(e)) if e.is_foreign_key_violation() => {
            Err(ScriptRepositoryError::NotFound(input.script_id))
        }
        Err(e) => Err(e.into()),
    }
}

/// Delete a route by id within an existing transaction.
///
/// Unlike the non-tx [`RouteRepository::delete`], this is intentionally
/// idempotent: a missing row is not an error. The only caller is the
/// reconcile engine (`ApplyService`), where "delete a route already gone"
/// (e.g. removed out-of-band between the diff read and the write) is a
/// no-op to converge on, not a failure to roll back the whole apply.
pub(crate) async fn delete_route_tx(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    route_id: Uuid,
) -> Result<(), ScriptRepositoryError> {
    sqlx::query("DELETE FROM routes WHERE id = $1")
        .bind(route_id)
        .execute(&mut **tx)
        .await?;
    Ok(())
}

#[derive(sqlx::FromRow)]
struct RouteRow {
    id: Uuid,
    app_id: Option<Uuid>,
    // `default` so any RETURNING/SELECT that predates the column still
    // hydrates; every query in this module now lists it explicitly.
    #[sqlx(default)]
    group_id: Option<Uuid>,
    script_id: Uuid,
    host_kind: String,
    host: String,
    host_param_name: Option<String>,
    path_kind: String,
    path: String,
    method: Option<String>,
    dispatch_mode: String,
    enabled: bool,
    // §11 tail: `default` so a SELECT/RETURNING that omits `sealed` still
    // hydrates (→ false). The queries that must see a true value — `list_effective`
    // (the rebuild gate) and the group-route load feeding the apply diff — list
    // it explicitly.
    #[sqlx(default)]
    sealed: bool,
    created_at: chrono::DateTime<chrono::Utc>,
}

/// Row shape for [`RouteRepository::list_effective`]: the effective app +
/// owner depth, with the underlying route columns flattened in via `flatten`.
#[derive(sqlx::FromRow)]
struct EffectiveRouteRow {
    effective_app_id: Uuid,
    depth: i32,
    #[sqlx(flatten)]
    row: RouteRow,
}

impl From<RouteRow> for Route {
    fn from(r: RouteRow) -> Self {
        Self {
            id: r.id,
            app_id: r.app_id.map(Into::into),
            group_id: r.group_id.map(Into::into),
            script_id: r.script_id.into(),
            host_kind: match r.host_kind.as_str() {
                "strict" => HostKind::Strict,
                "wildcard" => HostKind::Wildcard,
                _ => HostKind::Any,
            },
            host: r.host,
            host_param_name: r.host_param_name,
            path_kind: match r.path_kind.as_str() {
                "prefix" => PathKind::Prefix,
                "param" => PathKind::Param,
                _ => PathKind::Exact,
            },
            path: r.path,
            method: r.method,
            dispatch_mode: DispatchMode::from_wire(&r.dispatch_mode).unwrap_or(DispatchMode::Sync),
            enabled: r.enabled,
            sealed: r.sealed,
            created_at: r.created_at,
        }
    }
}
