//! Shared integration-test helpers.
//!
//! These tests need a live MongoDB. Each test process targets a unique database
//! (`normogen_test_<random>`), so parallel `cargo test` runs don't collide, and
//! drops it on completion. When Mongo is unreachable the tests skip gracefully
//! (printing a note) so `cargo test` stays green on machines without Mongo — the
//! CI job provides Mongo and runs them for real.

use std::sync::Arc;

use axum::{body::Body, http::Request, Router};
use mongodb::Client;
use normogen_backend::{
    app::build_app,
    auth::{JwtService, TokenVersionCache},
    config::{
        Config, CorsConfig, DatabaseConfig, EncryptionConfig, Environment, JwtConfig, ServerConfig,
    },
    db::MongoDb,
    models::{health_stats::HealthStatisticsRepository, refresh_token::RefreshTokenRepository},
    security, services,
};
use serde_json::Value;
use tower::util::ServiceExt;

/// Unique test DB name per process. Suffixing with a UUID keeps concurrent test
/// runs (local + CI) from stomping on each other.
pub fn test_db_name() -> String {
    format!("normogen_test_{}", uuid::Uuid::new_v4())
}

/// The Mongo URI to connect to during tests. Defaults to the local dev instance.
pub fn mongo_uri() -> String {
    std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".to_string())
}

/// Quick (~1s) reachability check so tests skip fast when Mongo is absent.
/// Builds a throwaway client with a short server-selection timeout and pings;
/// we don't use the real client afterwards (that's `MongoDb::new`).
pub async fn mongo_available() -> bool {
    let mut opts = match mongodb::options::ClientOptions::parse(&mongo_uri()).await {
        Ok(o) => o,
        Err(_) => return false,
    };
    opts.server_selection_timeout = Some(std::time::Duration::from_secs(1));
    opts.connect_timeout = Some(std::time::Duration::from_secs(1));
    let client = match Client::with_options(opts) {
        Ok(c) => c,
        Err(_) => return false,
    };
    client
        .database("admin")
        .run_command(mongodb::bson::doc! { "ping": 1 }, None)
        .await
        .is_ok()
}

/// A Config suitable for tests: development environment (so insecure-secret
/// defaults are allowed), short JWT expiries, a test JWT secret.
pub fn test_config(db_name: &str) -> Config {
    Config {
        server: ServerConfig {
            host: "127.0.0.1".to_string(),
            port: 0, // not bound in-process; tests use Router::oneshot
        },
        database: DatabaseConfig {
            uri: mongo_uri(),
            database: db_name.to_string(),
        },
        jwt: JwtConfig {
            secret: "test-secret-not-for-production".to_string(),
            access_token_expiry_minutes: 15,
            refresh_token_expiry_days: 7,
        },
        encryption: EncryptionConfig {
            key: "test-encryption-key".to_string(),
        },
        cors: CorsConfig {
            allowed_origins: vec!["http://localhost:3000".to_string()],
        },
        environment: Environment::Development,
    }
}

/// Build the full app against a fresh, isolated test database.
///
/// Returns `(router, db_name)` so callers can drop the database when done. The
/// router is the exact same one served in production (all routes + middleware),
/// just driven in-process via `oneshot`.
pub async fn app_for_test() -> Option<(Router, String)> {
    let db_name = test_db_name();

    // Fast, bounded connectivity probe: if Mongo isn't reachable, skip the test
    // in ~1s instead of waiting on `MongoDb::new`'s 10s server-selection
    // timeout (which would hang `cargo test` on machines without Mongo).
    if !mongo_available().await {
        eprintln!(
            "[integration] skipping: MongoDB unreachable at {}",
            mongo_uri()
        );
        return None;
    }

    let db = match MongoDb::new(&mongo_uri(), &db_name).await {
        Ok(db) => db,
        Err(e) => {
            eprintln!(
                "[integration] skipping: MongoDB connect failed at {}: {}",
                mongo_uri(),
                e
            );
            return None;
        }
    };

    let config = test_config(&db_name);
    let jwt_service = JwtService::new(config.jwt.clone());
    let database = db.get_database();

    // Best-effort index creation (mirrors main.rs).
    let _ = normogen_backend::db::DatabaseInitializer::new(database.clone())
        .initialize()
        .await;

    let token_version_cache = Arc::new(TokenVersionCache::with_default_ttl());
    let refresh_token_repo = Arc::new(RefreshTokenRepository::new(&database));
    let audit_logger = security::AuditLogger::new(&database);
    let session_manager = security::SessionManager::new(&database);
    let account_lockout = security::AccountLockout::new(database.collection("users"), 5, 15, 1440);
    let health_stats_repo = HealthStatisticsRepository::new(&database);
    let interaction_service = Arc::new(services::InteractionService::new());

    let state = normogen_backend::config::AppState {
        db,
        jwt_service,
        config: config.clone(),
        audit_logger: Some(audit_logger),
        session_manager: Some(session_manager),
        account_lockout: Some(account_lockout),
        health_stats_repo: Some(health_stats_repo),
        mongo_client: None,
        interaction_service: Some(interaction_service),
        token_version_cache,
        refresh_token_repo: Some(refresh_token_repo),
    };

    Some((build_app(state), db_name))
}

/// Drop a test database (best-effort teardown).
pub async fn drop_test_db(db_name: &str) {
    if let Ok(client) = Client::with_uri_str(&mongo_uri()).await {
        let _ = client.database(db_name).drop(None).await;
    }
}

/// Convenience: drive the router with a JSON request and return the status +
/// parsed JSON body.
pub async fn send_json(
    app: &Router,
    method: &str,
    uri: &str,
    body: Option<Value>,
    auth_token: Option<&str>,
) -> (u16, Value) {
    let mut builder = Request::builder().method(method).uri(uri);
    if let Some(token) = auth_token {
        builder = builder.header("Authorization", format!("Bearer {}", token));
    }
    let request = if let Some(json) = body {
        builder
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_vec(&json).unwrap()))
            .unwrap()
    } else {
        builder.body(Body::empty()).unwrap()
    };

    let response = app.clone().oneshot(request).await.unwrap();
    let status = response.status().as_u16();
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap_or_default();
    let json: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
    (status, json)
}
