from test_main import *
import pytest

@pytest.mark.order(1)
def test_register_user():
    response = client.post("/register", json={"username": "testuser", "password": "testpassword"})
    assert response.status_code == 200
    data = response.json()
    assert "access_token" in data
    assert "token_type" in data
    assert "user_id" in data

@pytest.mark.order(2)
def test_register_user_second():
    response = client.post("/register", json={"username": "testuser2", "password": "testpassword2"})
    assert response.status_code == 200
    data = response.json()
    assert "access_token" in data
    assert "token_type" in data
    assert "user_id" in data

def test_register_same_user():
    response = client.post("/register", json={"username": "testuser", "password": "testpassword"})
    assert response.status_code == 409 # Conflict - Cannot create two times the same user

def test_login_user():
    response = client.post("/login", data={"username": "testuser", "password": "testpassword"})
    assert response.status_code == 200
    data = response.json()
    assert "access_token" in data
    assert "token_type" in data
    assert "user_id" in data


def test_login_user_bad_password():
    response = client.post("/login", data={"username": "testuser", "password": "BADpassword"})
    assert response.status_code == 401 # Unauthorized, bad pwd

def test_search_users(token):
    response = client.get("/users?name=testuser", headers={"Authorization": f"Bearer {token}"})
    assert response.status_code == 200
    data = response.json()
    assert isinstance(data, list)
    assert data[0]["username"] == "testuser"

def test_search_users_unauthorized():
    response = client.get("/users?name=testuser", headers={"Authorization": "Bearer invalid_token"})
    assert response.status_code == 401
    
def test_search_users_false_regex(token):
    response = client.get("/users?name=*", headers={"Authorization": f"Bearer {token}"})
    assert response.status_code == 422

def test_get_user_by_id(token):
    # D'abord, on récupère l'ID d'un utilisateur existant
    search_response = client.get("/users?name=testuser", headers={"Authorization": f"Bearer {token}"})
    user_id = search_response.json()[0]["uid"]
    
    # Ensuite, on teste la récupération de cet utilisateur
    response = client.get(f"/user/{user_id}", headers={"Authorization": f"Bearer {token}"})
    assert response.status_code == 200
    data = response.json()
    assert data["username"] == "testuser"

def test_get_user_invalid_id(token):
    response = client.get("/user/invalid_id", headers={"Authorization": f"Bearer {token}"})
    assert response.status_code == 422

def test_get_user_not_found(token):
    # On utilise un ID qui n'existe probablement pas
    non_existent_id = "507f1f77bcf86cd799439011"
    response = client.get(f"/user/{non_existent_id}", headers={"Authorization": f"Bearer {token}"})
    assert response.status_code == 404