import pytest
from flask import session, g


class TestAuth:
    """Test authentication functionality."""

    def test_login_page(self, client):
        """Test that login page loads correctly."""
        response = client.get("/auth/login")
        assert response.status_code == 200
        assert b"Iniciar sesi" in response.data  # 'Iniciar sesión' in Spanish

    def test_login_success(self, client):
        """Test successful login with correct credentials."""
        response = client.post(
            "/auth/login",
            data={"username": "admin", "password": "admin123"},
            follow_redirects=True,
        )
        assert response.status_code == 200
        # Check that we're redirected to the right page after login
        assert b"Panel" in response.data or b"Proyectos" in response.data

    def test_login_invalid_credentials(self, client):
        """Test login with invalid credentials."""
        response = client.post(
            "/auth/login",
            data={"username": "admin", "password": "wrongpassword"},
            follow_redirects=True,
        )
        assert response.status_code == 200
        assert (
            b"credenciales" in response.data.lower()
        )  # Error message about credentials

    def test_logout(self, auth, client):
        """Test logout functionality."""
        # First login
        auth.login()

        # Then logout
        response = auth.logout()
        assert response.status_code == 200

        # Check if logged out - try to access a protected page
        response = client.get("/users/", follow_redirects=True)
        assert b"iniciar sesi" in response.data.lower()  # Should see login page

    def test_access_protected_route(self, client):
        """Test accessing a protected route without login."""
        # Try to access users list without login
        response = client.get("/users/", follow_redirects=True)
        assert response.status_code == 200
        assert b"iniciar sesi" in response.data.lower()  # Should be redirected to login

    def test_access_protected_route_with_login(self, logged_in_client):
        """Test accessing a protected route with login."""
        # Admin should be able to access users list
        response = logged_in_client.get("/admin/dashboard")
        assert response.status_code == 200

    def test_permission_levels(self, client, auth):
        """Test different permission levels."""
        # Login as regular user
        auth.login(username="user1", password="admin123")

        # Try to access admin-only page
        response = client.get("/admin/dashboard", follow_redirects=True)
        assert (
            response.status_code == 403 or b"acceso denegado" in response.data.lower()
        )
