"""
Test configuration and fixtures.
"""
import pytest
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.pool import StaticPool

from app.main import app
from app.core.database import Base, get_db
from app.core.security import create_access_token, hash_password
from app.models.models import User

# Use in-memory SQLite for testing
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"

test_engine = create_async_engine(
    TEST_DATABASE_URL,
    connect_args={"check_same_thread": False},
    poolclass=StaticPool,
)

TestAsyncSession = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)


@pytest.fixture(scope="session")
def anyio_backend():
    """Use asyncio for tests."""
    return "asyncio"


@pytest_asyncio.fixture(scope="function")
async def db_session():
    """Create test database and return session."""
    # Create all tables
    async with test_engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    
    # Create session and yield
    async with TestAsyncSession() as session:
        yield session
    
    # Cleanup
    async with test_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)


@pytest_asyncio.fixture(scope="function")
async def client(db_session):
    """Create test client using the same database session."""
    
    async def override_get_db():
        yield db_session
    
    app.dependency_overrides[get_db] = override_get_db
    
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
        yield ac
    
    # Clean up dependency overrides
    app.dependency_overrides.clear()


@pytest_asyncio.fixture
async def admin_user(db_session):
    """Create admin test user."""
    user = User(
        username="admin_test",
        email="admin@test.com",
        password_hash=hash_password("adminpassword123"),
        salt="test_salt",
        is_active=True,
        privlevel="Admin",
    )
    db_session.add(user)
    await db_session.flush()
    await db_session.refresh(user)
    return user


@pytest_asyncio.fixture
async def regular_user(db_session):
    """Create regular test user."""
    user = User(
        username="regular_test",
        email="user@test.com",
        password_hash=hash_password("testpassword123"),
        salt="test_salt",
        is_active=True,
        privlevel="User",
    )
    db_session.add(user)
    await db_session.flush()
    await db_session.refresh(user)
    return user


@pytest_asyncio.fixture
async def admin_token(admin_user):
    """Create admin access token with privlevel."""
    return create_access_token(str(admin_user.id), admin_user.privlevel or "User")


@pytest_asyncio.fixture
async def regular_token(regular_user):
    """Create regular user access token with privlevel."""
    return create_access_token(str(regular_user.id), regular_user.privlevel or "User")


@pytest_asyncio.fixture
async def admin_headers(admin_token):
    """Get admin auth headers."""
    return {"Authorization": f"Bearer {admin_token}"}


@pytest_asyncio.fixture
async def regular_headers(regular_token):
    """Get regular user auth headers."""
    return {"Authorization": f"Bearer {regular_token}"}


@pytest_asyncio.fixture
async def test_user(regular_user):
    """Alias for regular_user."""
    return regular_user


@pytest_asyncio.fixture
async def auth_headers(regular_headers):
    """Alias for regular_headers."""
    return regular_headers
