"""
Tests pour les endpoints API
"""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from backend.app.main import app
from backend.app.core.database import Base, get_db
from backend.app.models.ip import IP


# Setup DB de test
@pytest.fixture
def test_db():
    """Fixture base de données de test"""
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    TestingSessionLocal = sessionmaker(bind=engine)
    return TestingSessionLocal


@pytest.fixture
def client(test_db):
    """Fixture client de test"""
    def override_get_db():
        db = test_db()
        try:
            yield db
        finally:
            db.close()

    app.dependency_overrides[get_db] = override_get_db
    return TestClient(app)


class TestAPIEndpoints:
    """Tests pour les endpoints API"""

    def test_root_endpoint(self, client):
        """Test endpoint racine"""
        response = client.get("/")
        assert response.status_code == 200
        data = response.json()
        assert "name" in data
        assert data["name"] == "IPWatch API"

    def test_health_check(self, client):
        """Test health check"""
        response = client.get("/health")
        assert response.status_code == 200
        data = response.json()
        assert "status" in data
        assert data["status"] == "healthy"

    def test_get_all_ips_empty(self, client):
        """Test récupération IPs (vide)"""
        response = client.get("/api/ips/")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        assert len(data) == 0

    def test_get_stats_empty(self, client):
        """Test stats avec DB vide"""
        response = client.get("/api/ips/stats/summary")
        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 0
        assert data["online"] == 0
        assert data["offline"] == 0

    def test_get_ip_not_found(self, client):
        """Test récupération IP inexistante"""
        response = client.get("/api/ips/192.168.1.100")
        assert response.status_code == 404

    def test_update_ip(self, client, test_db):
        """Test mise à jour IP"""
        # Créer d'abord une IP
        db = test_db()
        ip = IP(
            ip="192.168.1.100",
            name="Test",
            known=False,
            last_status="online"
        )
        db.add(ip)
        db.commit()
        db.close()

        # Mettre à jour via API
        update_data = {
            "name": "Updated Name",
            "known": True,
            "location": "Bureau"
        }

        response = client.put("/api/ips/192.168.1.100", json=update_data)
        assert response.status_code == 200

        data = response.json()
        assert data["name"] == "Updated Name"
        assert data["known"] is True
        assert data["location"] == "Bureau"

    def test_delete_ip(self, client, test_db):
        """Test suppression IP"""
        # Créer une IP
        db = test_db()
        ip = IP(ip="192.168.1.101", last_status="online")
        db.add(ip)
        db.commit()
        db.close()

        # Supprimer via API
        response = client.delete("/api/ips/192.168.1.101")
        assert response.status_code == 200

        # Vérifier suppression
        response = client.get("/api/ips/192.168.1.101")
        assert response.status_code == 404
