

@pytest.fixture(scope="session")
def db_engine(test_app):
    from sqlalchemy import create_engine

    eng = create_engine(TEST_DATABASE_URL, pool_pre_ping=True)
    yield eng
    eng.dispose()


@pytest.fixture()
def db(db_engine):
    """Plain sync session on the test DB (for direct row assertions)."""
    from sqlalchemy.orm import Session

    with Session(db_engine, expire_on_commit=False) as s:
        yield s


def csrf_of(client) -> str:
    """Read the CSRF token from the client's cookie jar."""
    for c in client.cookies.jar:
        if c.name == "mailer_csrf":
            return c.value
    raise AssertionError("CSRF cookie missing after login")


@pytest.fixture()
def second_user(test_app):
    """A second, independent registered+logged-in user (for isolation tests)."""
    from fastapi.testclient import TestClient

    with TestClient(test_app) as client:
        em = f"u2_{uuid.uuid4().hex[:10]}@example.com"
        pw = "Second#Pass99"
        r = client.post("/auth/register", json={"email": em, "password": pw,
                                                "full_name": "Second"})
        assert r.status_code in (200, 201), r.text[:300]
        r = client.post("/auth/login", json={"email": em, "password": pw})
        assert r.status_code == 200, r.text[:300]
        yield client


@pytest.fixture()
def fresh_db(db_engine):
    """Fresh sync session AFTER truncation — request when seeding for another
    user's data must not race the api fixture's truncation."""
    from sqlalchemy.orm import Session

    with Session(db_engine, expire_on_commit=False) as s:
        yield s
