import pytest
import json
import os


class TestUserManagement:
    """Test user management functionality."""

    def test_list_users(self, logged_in_client):
        """Test listing users."""
        response = logged_in_client.get("/users/")
        assert response.status_code == 200
        assert b"Usuarios del Sistema" in response.data
        # Check for existing users
        assert b"admin" in response.data
        assert b"user1" in response.data

    def test_create_user(self, logged_in_client, app):
        """Test creating a new user."""
        response = logged_in_client.post(
            "/users/create",
            data={
                "nombre": "Usuario de Prueba",
                "username": "testuser",
                "email": "test@example.com",
                "password": "password123",
                "password_confirm": "password123",
                "nivel": 1000,
                "idioma": "es",
                "empresa": "Empresa Test",
                "estado": "activo",
                "fecha_caducidad": "",
            },
            follow_redirects=True,
        )

        assert response.status_code == 200

        # Check if user was created
        with app.app_context():
            users_path = os.path.join(app.config["STORAGE_PATH"], "users", "users.json")
            with open(users_path, "r") as f:
                users = json.load(f)
                assert "testuser" in users
                assert users["testuser"]["nombre"] == "Usuario de Prueba"
                assert users["testuser"]["email"] == "test@example.com"
                assert users["testuser"]["nivel"] == 1000

    def test_edit_user(self, logged_in_client, app):
        """Test editing an existing user."""
        # First create a user to edit
        logged_in_client.post(
            "/users/create",
            data={
                "nombre": "Usuario para Editar",
                "username": "edit_user",
                "email": "edit@example.com",
                "password": "password123",
                "password_confirm": "password123",
                "nivel": 1000,
                "idioma": "es",
                "empresa": "Empresa Original",
                "estado": "activo",
                "fecha_caducidad": "",
            },
            follow_redirects=True,
        )

        # Now edit the user
        response = logged_in_client.post(
            "/users/edit/edit_user",
            data={
                "nombre": "Usuario Editado",
                "email": "edited@example.com",
                "password": "",  # Empty password means no change
                "password_confirm": "",
                "nivel": 5000,  # Changed level
                "idioma": "en",  # Changed language
                "empresa": "Empresa Modificada",
                "estado": "activo",
                "fecha_caducidad": "",
            },
            follow_redirects=True,
        )

        assert response.status_code == 200

        # Verify changes
        with app.app_context():
            users_path = os.path.join(app.config["STORAGE_PATH"], "users", "users.json")
            with open(users_path, "r") as f:
                users = json.load(f)
                assert "edit_user" in users
                assert users["edit_user"]["nombre"] == "Usuario Editado"
                assert users["edit_user"]["email"] == "edited@example.com"
                assert users["edit_user"]["nivel"] == 5000
                assert users["edit_user"]["idioma"] == "en"
                assert users["edit_user"]["empresa"] == "Empresa Modificada"

    def test_delete_user(self, logged_in_client, app):
        """Test deleting a user."""
        # First create a user to delete
        logged_in_client.post(
            "/users/create",
            data={
                "nombre": "Usuario para Eliminar",
                "username": "delete_user",
                "email": "delete@example.com",
                "password": "password123",
                "password_confirm": "password123",
                "nivel": 1000,
                "idioma": "es",
                "empresa": "Empresa Test",
                "estado": "activo",
                "fecha_caducidad": "",
            },
            follow_redirects=True,
        )

        # Verify user was created
        with app.app_context():
            users_path = os.path.join(app.config["STORAGE_PATH"], "users", "users.json")
            with open(users_path, "r") as f:
                users = json.load(f)
                assert "delete_user" in users

        # Now delete the user
        response = logged_in_client.post(
            "/users/delete/delete_user", follow_redirects=True
        )

        assert response.status_code == 200

        # Verify user was deleted
        with app.app_context():
            users_path = os.path.join(app.config["STORAGE_PATH"], "users", "users.json")
            with open(users_path, "r") as f:
                users = json.load(f)
                assert "delete_user" not in users

    def test_cannot_delete_admin(self, logged_in_client):
        """Test that admin user cannot be deleted."""
        response = logged_in_client.post("/users/delete/admin", follow_redirects=True)
        assert response.status_code == 200

        # Should see an error message
        assert b"No se puede eliminar" in response.data or b"no puede" in response.data
