import os

os.environ.setdefault("DATABASE_URL", "sqlite+pysqlite:///:memory:")
os.environ.setdefault("EMAIL_DELIVERY_MODE", "memory")

from fastapi.testclient import TestClient
import pytest

from app.core import database as db_module
from app.core.email import memory_mailer
from app.core.storage import memory_store
from app.db.base import Base
from app.db.seed import run_seed
from app.main import app


@pytest.fixture(scope="session", autouse=True)
def setup_database():
    Base.metadata.create_all(db_module.engine)
    run_seed(include_demo_pages=False)
    yield
    Base.metadata.drop_all(db_module.engine)


@pytest.fixture(autouse=True)
def disable_rate_limits(monkeypatch):
    from app.core.config import settings

    monkeypatch.setattr(settings, "enable_rate_limit", False)
    monkeypatch.setattr(settings, "email_delivery_mode", "memory")
    monkeypatch.setattr(settings, "storage_mode", "memory")


@pytest.fixture(autouse=True)
def clear_email_outbox():
    memory_mailer.clear()
    yield
    memory_mailer.clear()


@pytest.fixture(autouse=True)
def clear_storage():
    memory_store.clear()
    yield
    memory_store.clear()


@pytest.fixture()
def client() -> TestClient:
    return TestClient(app)
