mod common;

use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::util::ServiceExt;

use common::{TestConfig, test_user};

#[tokio::test]
async fn valid_api_key_returns_user() {
    let app =
        doctate_server::create_router(TestConfig::new().with_user(test_user("dr_test")).build());

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/debug/whoami")
                .header("X-API-Key", "key-dr_test")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

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

    let json = common::body_json(response).await;
    assert_eq!(json["slug"], "dr_test");
    assert_eq!(json["role"], "doctor");
}

#[tokio::test]
async fn invalid_api_key_returns_401() {
    let app =
        doctate_server::create_router(TestConfig::new().with_user(test_user("dr_test")).build());

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/debug/whoami")
                .header("X-API-Key", "wrong-key")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

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

#[tokio::test]
async fn missing_api_key_returns_401() {
    let app =
        doctate_server::create_router(TestConfig::new().with_user(test_user("dr_test")).build());

    let response = app
        .oneshot(
            Request::builder()
                .uri("/api/debug/whoami")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

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