use api::{AppState, build_app, migrate_sessions};
use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use db::users;
use domain::{AuditActor, Email, NewUser, ObjectId, Role};
use http_body_util::BodyExt;
use search::SearchClient;
use sqlx::PgPool;
use tower::ServiceExt;

fn meili() -> (String, String) {
    (
        std::env::var("MEILI_URL").expect("MEILI_URL must be set"),
        std::env::var("MEILI_MASTER_KEY").expect("MEILI_MASTER_KEY must be set"),
    )
}

fn unique_index() -> String {
    format!("api_reindex_test_{}", uuid::Uuid::new_v4().simple())
}

fn state(pool: PgPool, search: SearchClient) -> AppState {
    AppState {
        db: db::Db::from_pool(pool),
        app_name: "Test".into(),
        cookie_secure: false,
        search: Some(search),
        default_language: "sv".into(),
        default_timezone: "Europe/Stockholm".into(),
    }
}

async fn seed_user(pool: &PgPool, email: &str, password: &str, role: Role) {
    let db = db::Db::from_pool(pool.clone());
    let mut tx = db.pool().begin().await.unwrap();

    users::create_user(
        &mut tx,
        AuditActor::System,
        &NewUser {
            email: Email::parse(email).unwrap(),
            password_hash: auth::hash_password(password).unwrap(),
            role,
        },
    )
    .await
    .unwrap();

    tx.commit().await.unwrap();
}

async fn login(app: &axum::Router, email: &str, password: &str) -> String {
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/admin/login")
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(format!(
                    r#"{{"email":"{email}","password":"{password}"}}"#
                )))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::NO_CONTENT);

    resp.headers()
        .get(header::SET_COOKIE)
        .unwrap()
        .to_str()
        .unwrap()
        .split(';')
        .next()
        .unwrap()
        .to_owned()
}

#[sqlx::test(migrations = "../db/migrations")]
async fn admin_writes_sync_the_search_index(pool: PgPool) {
    migrate_sessions(&db::Db::from_pool(pool.clone()))
        .await
        .unwrap();

    seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await;

    let (url, key) = meili();
    let search = SearchClient::connect(&url, &key, &unique_index()).unwrap();

    search.ensure_index().await.unwrap();

    // a second handle to the same index, used to observe what the handlers indexed
    let observer = search.clone();

    let app = build_app(state(pool.clone(), search));
    let cookie = login(&app, "ed@example.com", "pw-editor-123").await;

    // create via the admin API -> the object is indexed on commit
    let create = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/admin/objects")
                .header(header::COOKIE, &cookie)
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(
                    r#"{"object_number":"R-1","object_name":"astrolabe","number_of_objects":1,"visibility":"internal"}"#,
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(create.status(), StatusCode::CREATED);

    let created: serde_json::Value =
        serde_json::from_slice(&create.into_body().collect().await.unwrap().to_bytes()).unwrap();
    let id: ObjectId = created["id"].as_str().unwrap().parse().unwrap();

    assert_eq!(observer.search("astrolabe").await.unwrap(), vec![id]);

    // delete via the admin API -> the object drops out of the index
    let delete = app
        .oneshot(
            Request::builder()
                .method("DELETE")
                .uri(format!("/api/admin/objects/{id}"))
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(delete.status(), StatusCode::NO_CONTENT);

    assert!(observer.search("astrolabe").await.unwrap().is_empty());
}
