"""
Shared test setup.

API calls in the tests run as the first active ADMIN user in the database, so the
permission checks behave exactly as they do for a signed-in administrator.
"""
import pytest
from fastapi import HTTPException
from sqlalchemy import select

from app.main import app
from app.core.database import AsyncSessionLocal
from app.core.security import get_current_user
from app.models.core_models import LoginUsers


async def _admin_user() -> LoginUsers:
    async with AsyncSessionLocal() as db:
        user = (await db.execute(
            select(LoginUsers)
            .where(LoginUsers.role_code == 'ADMIN', LoginUsers.is_active.is_(True))
            .limit(1)
        )).scalar_one_or_none()
    if user is None:
        raise HTTPException(status_code=401, detail='Tests need an active ADMIN user in the database')
    return user


@pytest.fixture(autouse=True)
def signed_in_as_admin():
    app.dependency_overrides[get_current_user] = _admin_user
    yield
    app.dependency_overrides.pop(get_current_user, None)
