import pytest
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).absolute().parent.parent))

# TestClient provided by FastAPI
from fastapi.testclient import TestClient

# PyMongo for the database
import pymongo

# Contains all constants
import app.config as config
# Import the app
from app.main import app

# Database setup
client = pymongo.MongoClient(config.MONGODB_URL, username=config.MONGODB_USERNAME, password=config.MONGODB_PASSWORD)

# Drop test database if exists
if config.MONGODB_DATABASE in client.list_database_names():
    try:
        client.drop_database(config.MONGODB_DATABASE)
    except Exception as e:
        print(f"Error with database : {e}")

# Create empty database
db = client[config.MONGODB_DATABASE]

# TestClient with the app imported from main
client = TestClient(app)

@pytest.fixture
def token():
    login_response = client.post("/login", data={"username": "testuser", "password": "testpassword"})
    token = login_response.json()["access_token"]
    return token

@pytest.fixture
def token_second():
    login_response = client.post("/login", data={"username": "testuser2", "password": "testpassword2"})
    token = login_response.json()["access_token"]
    return token

@pytest.fixture
def user_id():
    login_response = client.post("/login", data={"username": "testuser", "password": "testpassword"})
    user_id = login_response.json()["user_id"]
    return user_id

@pytest.fixture
def user_id_second():
    login_response = client.post("/login", data={"username": "testuser2", "password": "testpassword2"})
    user_id = login_response.json()["user_id"]
    return user_id