import os
import httpx
import pytest

BASE_URL = os.getenv("SYNC_TEST_BASE_URL", "http://127.0.0.1:8002/api/v1")
ADMIN_EMAIL = os.getenv("SUPER_ADMINS", "admin@jerxie.com").split(',')[0]
ADMIN_PASSWORD = os.getenv("CORTEX_ADMIN_PASSWORD", "admin")

def test_login_success():
    """
    Simulates the first user CUJ: Login test using password.
    Valid credentials should return an access token.
    """
    login_data = {
        "email": ADMIN_EMAIL,
        "password": ADMIN_PASSWORD
    }
    with httpx.Client(timeout=10.0) as client:
        r = client.post(f"{BASE_URL}/users/login/local", json=login_data)
        
        assert r.status_code == 200, f"Expected 200 OK, got {r.status_code}: {r.text}"
        
        json_data = r.json()
        assert "user_id" in json_data, "Response missing 'user_id'"
        assert json_data["email"] == ADMIN_EMAIL, "Response email does not match admin email"

def test_login_failure_invalid_password():
    """
    Simulates a login failure with incorrect password.
    """
    login_data = {
        "email": ADMIN_EMAIL,
        "password": "WrongPassword123!"
    }
    with httpx.Client(timeout=10.0) as client:
        r = client.post(f"{BASE_URL}/users/login/local", json=login_data)
        
        # FastAPI typically uses 401 for invalid credentials
        assert r.status_code == 401, f"Expected 401 Unauthorized, got {r.status_code}"

def test_login_failure_invalid_user():
    """
    Simulates a login failure with an unknown email.
    """
    login_data = {
        "email": "ghost@jerxie.com",
        "password": ADMIN_PASSWORD
    }
    with httpx.Client(timeout=10.0) as client:
        r = client.post(f"{BASE_URL}/users/login/local", json=login_data)
        
        assert r.status_code == 401, f"Expected 401 Unauthorized, got {r.status_code}"
