import pytest


def test_login_page(client):
    """La page de login doit répondre 200."""
    response = client.get('/auth/login')
    assert response.status_code == 200
    data = response.data.decode('utf-8').lower()
    assert 'login' in data or 'connexion' in data or "nom d'utilisateur" in data


def test_root_redirects_to_login_when_anonymous(client):
    """La racine redirige vers login si non connecté."""
    response = client.get('/')
    assert response.status_code in (302, 401)
    if response.status_code == 302:
        assert '/auth/login' in response.location


def test_login_post_success(client, app):
    """Un utilisateur valide peut se connecter (POST)."""
    from app_new import db
    from app_new.core.models.user import User

    with app.app_context():
        user = User(
            username='testuser',
            email='testuser@gmao.local',
            full_name='Utilisateur test',
            role='user',
            is_active=True,
        )
        user.set_password('secret123')
        db.session.add(user)
        db.session.commit()

    response = client.post('/auth/login', data={
        'username': 'testuser',
        'password': 'secret123',
    })
    assert response.status_code == 302
    with client.session_transaction() as session:
        assert session.get('_user_id') is not None


def test_login_post_failure(client):
    """Un mauvais mot de passe est rejeté (POST)."""
    client.get('/auth/logout')  # forcer la déconnexion avant le test
    response = client.post('/auth/login', data={
        'username': 'inconnu',
        'password': 'mauvais',
    }, follow_redirects=True)
    assert response.status_code == 200
    data = response.data.decode('utf-8').lower()
    assert 'incorrect' in data or 'invalide' in data or "nom d'utilisateur" in data
