from fastapi import HTTPException
import pytest
from fastapi.testclient import TestClient
from datetime import timedelta
from app.main import app
from app.core.security import create_access_token, verify_token
import time

client = TestClient(app)

SECRET_KEY = "testsecret"
ALGORITHM = "HS256"

def test_create_access_token():
    data = {"sub": "testuser"}
    token = create_access_token(data, expires_delta=timedelta(minutes=1))
    assert isinstance(token, str)

def test_verify_token_valid():
    data = {"sub": "testuser"}
    token = create_access_token(data, expires_delta=timedelta(minutes=1))
    payload = verify_token(token)
    assert payload["sub"] == "testuser"

def test_verify_token_expired():
    data = {"sub": "testuser"}
    token = create_access_token(data, expires_delta=timedelta(seconds=1))
    time.sleep(3)
    with pytest.raises(HTTPException) as exc_info:
        verify_token(token)
    assert exc_info.value.status_code == 401
    assert exc_info.value.detail == "Token expirat"

def test_verify_token_invalid():
    invalid_token = "invalid.token.value"
    with pytest.raises(Exception):
        verify_token(invalid_token)

def test_login_success():
    response = client.post(
        "/login",
        data={"username": "professor1@uni.edu", "password": "1234"}
    )
    assert response.status_code == 200
    assert "access_token" in response.json()

def test_login_failure():
    response = client.post(
        "/login",
        data={"username": "invalid_user", "password": "wrong_password"}
    )
    assert response.status_code == 400
    assert response.json()["detail"] == "Usuari o contrasenya incorrectes"
