import os

# Deterministic unit-test config — must be set before app.config is imported
# (env vars beat the .env file that pydantic-settings would otherwise read).
os.environ["SNAPSHOT_ENABLED"] = "false"
os.environ["WITH_DB_URL"] = ""

# Auth-flow test config. bw_auth reads these lazily at call time. BW_AUTH
# points at an unroutable host so an accidental real network call fails fast
# instead of hitting production id-auth.
os.environ["APP_ENV"] = "test"
os.environ["BW_CLIENT_ID"] = "withtest"
os.environ["BW_CLIENT_SECRET"] = "unit-test-secret-not-a-real-one"
os.environ["BW_APP_DOMAIN"] = "https://testserver"
os.environ["BW_AUTH"] = "https://bw-auth.invalid"
os.environ.pop("AUTH_DEV_USER", None)
os.environ.pop("SESSION_SECRET", None)

import pytest
from fastapi.testclient import TestClient

from app.main import create_app
from app.services.auth import session as auth_session


@pytest.fixture()
def client():
    # https base_url: the app's cookies are Secure, and httpx's jar
    # (correctly) refuses to send Secure cookies over plain http.
    with TestClient(create_app(), base_url="https://testserver") as test_client:
        yield test_client


@pytest.fixture()
def authed_client(client):
    """A client holding a valid signed app-session cookie (no DB row —
    fine for endpoints that read only the session claims)."""
    token = auth_session.mint_session(
        username="rian", email="rian@rian.ca", is_super_admin=True
    )
    client.cookies.set(auth_session.SESSION_COOKIE, token)
    return client


@pytest.fixture()
def db_engine(monkeypatch):
    """In-memory SQLite standing in for the sidecar Postgres, patched into
    app.db.get_engine so the callback's provisioning writes land here."""
    from sqlalchemy import create_engine
    from sqlalchemy.pool import StaticPool

    from app import db as app_db
    from app.models import Base

    engine = create_engine(
        "sqlite://",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    Base.metadata.create_all(engine)
    monkeypatch.setattr(app_db, "get_engine", lambda: engine)
    yield engine
    engine.dispose()
