"""
Test di integrazione per gli endpoint utenti.
"""

import os
import pytest

os.environ.setdefault("ENCRYPTION_KEY", "b" * 64)
os.environ.setdefault("SECRET_KEY", "integration-test-secret-key-only-for-tests")


class TestUsersEndpoint:
    @pytest.mark.asyncio
    async def test_list_users_admin(self, client, admin_token):
        response = await client.get(
            "/api/v1/users",
            headers={"Authorization": f"Bearer {admin_token}"},
        )
        assert response.status_code == 200
        data = response.json()
        assert "items" in data
        assert "total" in data
        assert data["total"] >= 1  # almeno l'admin stesso

    @pytest.mark.asyncio
    async def test_list_users_no_auth_returns_403(self, client):
        response = await client.get("/api/v1/users")
        assert response.status_code == 403

    @pytest.mark.asyncio
    async def test_create_user_success(self, client, admin_token):
        response = await client.post(
            "/api/v1/users",
            headers={"Authorization": f"Bearer {admin_token}"},
            json={
                "email": "newuser@test.com",
                "password": "NewUser1!",
                "full_name": "Nuovo Utente",
                "role": "operator",
            },
        )
        assert response.status_code == 201
        data = response.json()
        assert data["email"] == "newuser@test.com"
        assert data["role"] == "operator"
        assert "password_hash" not in data  # non deve esporre hash

    @pytest.mark.asyncio
    async def test_create_user_duplicate_email_returns_409(self, client, admin_token):
        # Crea primo utente
        await client.post(
            "/api/v1/users",
            headers={"Authorization": f"Bearer {admin_token}"},
            json={
                "email": "duplicate@test.com",
                "password": "DupUser1!",
                "full_name": "Dup User",
                "role": "operator",
            },
        )
        # Secondo tentativo con stessa email
        response = await client.post(
            "/api/v1/users",
            headers={"Authorization": f"Bearer {admin_token}"},
            json={
                "email": "duplicate@test.com",
                "password": "DupUser1!",
                "full_name": "Dup User 2",
                "role": "operator",
            },
        )
        assert response.status_code == 409

    @pytest.mark.asyncio
    async def test_create_superadmin_forbidden(self, client, admin_token):
        response = await client.post(
            "/api/v1/users",
            headers={"Authorization": f"Bearer {admin_token}"},
            json={
                "email": "sadmin@test.com",
                "password": "SuperAdmin1!",
                "full_name": "Super",
                "role": "super_admin",
            },
        )
        # Il validator Pydantic blocca la creazione di super_admin
        assert response.status_code in (400, 422)

    @pytest.mark.asyncio
    async def test_create_user_weak_password_returns_422(self, client, admin_token):
        response = await client.post(
            "/api/v1/users",
            headers={"Authorization": f"Bearer {admin_token}"},
            json={
                "email": "weakpwd@test.com",
                "password": "weak",  # troppo corta e senza maiuscole/numeri
                "full_name": "Weak Pwd User",
                "role": "operator",
            },
        )
        assert response.status_code == 422

    @pytest.mark.asyncio
    async def test_get_user_by_id(self, client, admin_token, admin_user):
        response = await client.get(
            f"/api/v1/users/{admin_user.id}",
            headers={"Authorization": f"Bearer {admin_token}"},
        )
        assert response.status_code == 200
        data = response.json()
        assert data["id"] == str(admin_user.id)

    @pytest.mark.asyncio
    async def test_get_nonexistent_user_returns_404(self, client, admin_token):
        import uuid
        fake_id = uuid.uuid4()
        response = await client.get(
            f"/api/v1/users/{fake_id}",
            headers={"Authorization": f"Bearer {admin_token}"},
        )
        assert response.status_code == 404

    @pytest.mark.asyncio
    async def test_update_user(self, client, admin_token, admin_user):
        response = await client.patch(
            f"/api/v1/users/{admin_user.id}",
            headers={"Authorization": f"Bearer {admin_token}"},
            json={"full_name": "Admin Aggiornato"},
        )
        assert response.status_code == 200
        assert response.json()["full_name"] == "Admin Aggiornato"
