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, 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_search_test_{}", uuid::Uuid::new_v4().simple())
}

fn state(pool: PgPool, search: Option<SearchClient>) -> AppState {
    AppState {
        db: db::Db::from_pool(pool),
        app_name: "Test".into(),
        cookie_secure: false,
        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 search_requires_auth(pool: PgPool) {
    migrate_sessions(&db::Db::from_pool(pool.clone()))
        .await
        .unwrap();

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

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

    let app = build_app(state(pool, Some(search)));

    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/admin/search?q=bronze")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[sqlx::test(migrations = "../db/migrations")]
async fn search_returns_results_and_validates_params(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();

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

    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 resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/api/admin/search?q=astrolabe")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

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

    let body: serde_json::Value =
        serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();

    assert_eq!(body["estimated_total"], 1);
    assert_eq!(body["hits"][0]["object_name"], "astrolabe");

    let empty = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/api/admin/search?q=")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(empty.status(), StatusCode::OK);

    let empty_body: serde_json::Value =
        serde_json::from_slice(&empty.into_body().collect().await.unwrap().to_bytes()).unwrap();

    assert_eq!(empty_body["estimated_total"], 0);

    let bad = app
        .oneshot(
            Request::builder()
                .uri("/api/admin/search?q=astrolabe&visibility=bogus")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(bad.status(), StatusCode::BAD_REQUEST);
}

#[sqlx::test(migrations = "../db/migrations")]
async fn search_visibility_filter_narrows_results(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();

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

    let create_internal = 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-2","object_name":"astrolabe-internal","number_of_objects":1,"visibility":"internal"}"#,
                ))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(create_internal.status(), StatusCode::CREATED);

    let create_draft = 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-3","object_name":"astrolabe-draft","number_of_objects":1,"visibility":"draft"}"#,
                ))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(create_draft.status(), StatusCode::CREATED);

    let all = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/api/admin/search?q=astrolabe")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(all.status(), StatusCode::OK);

    let all_body: serde_json::Value =
        serde_json::from_slice(&all.into_body().collect().await.unwrap().to_bytes()).unwrap();

    assert_eq!(all_body["estimated_total"], 2);

    let filtered = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/api/admin/search?q=astrolabe&visibility=internal")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(filtered.status(), StatusCode::OK);

    let filtered_body: serde_json::Value =
        serde_json::from_slice(&filtered.into_body().collect().await.unwrap().to_bytes()).unwrap();

    assert_eq!(filtered_body["estimated_total"], 1);
    assert_eq!(filtered_body["hits"][0]["visibility"], "internal");
}

#[sqlx::test(migrations = "../db/migrations")]
async fn search_unavailable_when_not_configured(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 app = build_app(state(pool, None));
    let cookie = login(&app, "ed@example.com", "pw-editor-123").await;

    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/admin/search?q=bronze")
                .header(header::COOKIE, &cookie)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
}
