"""Nexus — Test Configuration (pytest + async fixtures)

Fixed: wired up dependency_overrides properly,
added test Redis mock, added admin fixture for JWT auth tests.
"""

import asyncio
import pytest
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession

from server.domain.models import Base, Admin
from server.config import settings

# Use in-memory SQLite for unit/integration tests
TEST_DATABASE_URL = "sqlite+aiosqlite://"


@pytest.fixture(scope="session")
def event_loop():
    loop = asyncio.new_event_loop()
    yield loop
    loop.close()


@pytest.fixture(scope="session")
async def test_engine():
    engine = create_async_engine(TEST_DATABASE_URL, echo=False)
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield engine
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await engine.dispose()


@pytest.fixture(scope="function")
async def db_session(test_engine):
    session_factory = async_sessionmaker(test_engine, class_=AsyncSession)
    session = session_factory()
    try:
        yield session
    finally:
        await session.close()


@pytest.fixture(scope="function")
async def api_client(db_session):
    """Create an async HTTP client for API integration tests"""
    from server.main import app
    from server.api.dependencies import get_db

    async def override_get_session():
        yield db_session

    app.dependency_overrides[get_db] = override_get_session

    transport = ASGITransport(app=app)
    client = AsyncClient(transport=transport, base_url="http://test")
    yield client
    await client.aclose()
    app.dependency_overrides.clear()


@pytest.fixture
async def test_admin(db_session):
    """Create a test admin user and return with JWT token"""
    import bcrypt
    from server.application.services.auth_service import AuthService
    from server.infrastructure.database.admin_repo import AdminRepositoryImpl
    from server.infrastructure.database.audit_log_repo import AuditLogRepositoryImpl

    # LoginAttemptRepositoryImpl requires login_attempt_repo which may not exist in test DB
    # Use a simple mock approach
    from unittest.mock import MagicMock

    password_hash = bcrypt.hashpw("test123".encode(), bcrypt.gensalt()).decode()
    admin = Admin(
        username="testadmin",
        password_hash=password_hash,
        is_active=True,
        totp_enabled=False,
    )
    db_session.add(admin)
    await db_session.commit()
    await db_session.refresh(admin)

    auth_service = AuthService(
        admin_repo=AdminRepositoryImpl(db_session),
        attempt_repo=MagicMock(),
        audit_repo=AuditLogRepositoryImpl(db_session),
    )
    token = auth_service._create_access_token(admin)

    return {"admin": admin, "token": token}
