extern crate regex;
extern crate reqwest;
#[macro_use]
extern crate serde_json;

use reqwest::{Client, Response, StatusCode};
use serde_json::Value;

mod common;

//Credentials = collections.namedtuple('Credentials', ['username', 'password'])
//
//
//@pytest.fixture(scope='module')
//def valid_user(db):
//    test_user, password = utils.generate_test_user(db)
//    return Credentials(test_user.username, password)

#[test]
#[ignore]
fn test_valid_user_with_valid_credentials_can_authenticate_on_site() {
    //        api_base_uri, valid_user):
    //
    //    response = requests.post(f'{api_base_uri}/auth', json={
    //        'username': valid_user.username,
    //        'password': valid_user.password,
    //    })
    //
    //    assert response.status_code == http.HTTPStatus.OK
    //
    //    jwt_token = response.json()['access_token']
    //    assert jwt_token is not None
    //    decoded_jwt = jwt.decode(jwt_token, verify=False)
    //    assert 'identity' in decoded_jwt
    //
    //    actual_user = response.json().get('user')
    //    assert actual_user['username'] == valid_user.username
}

#[test]
#[ignore]
fn test_valid_user_with_invalid_credentials_cannot_authenticate_on_site() {
    //        api_base_uri, valid_user):
    //
    //    response = requests.post(f'{api_base_uri}/auth', json={
    //        'username': valid_user.username,
    //        'password': 'random_password',
    //    })
    //    assert_unauthorized_response(response)
}

#[test]
fn test_invalid_user_with_invalid_credentials_cannot_authenticate_on_site() {
    let api_base_uri = common::api_base_url();
    let test_client = Client::new();
    let auth_url = api_base_uri.join("/auth").unwrap();

    let credentials = json!({"username": "random_user", "password": "random_password"});

    let actual_response = test_client
        .post(auth_url)
        .json(&credentials)
        .send()
        .unwrap();

    assert_unauthorized_response(actual_response);
}

fn assert_unauthorized_response(mut actual_response: Response) {
    let expected_json = json!({
        "error": {
            "message": "Invalid credentials provided.",
            "status_code": 401,
        },
    });

    assert_eq!(actual_response.status(), StatusCode::Unauthorized);
    let actual_response_json: Value = actual_response.json().unwrap();
    assert_eq!(actual_response_json, expected_json);
}
