import pytest
from fastapi.testclient import TestClient
from sqlmodel import Session, SQLModel, create_engine
from sqlmodel.pool import StaticPool

from main import app
from database import get_session
from models import User, Vertical

# Use in-memory SQLite for testing
sqlite_file_name = "database.db"
sqlite_url = f"sqlite://"

engine = create_engine(
    sqlite_url, 
    connect_args={"check_same_thread": False}, 
    poolclass=StaticPool
)

@pytest.fixture(name="session")
def session_fixture():
    engine = create_engine(
        "sqlite://", 
        connect_args={"check_same_thread": False}, 
        poolclass=StaticPool
    )
    SQLModel.metadata.create_all(engine)
    with Session(engine) as session:
        yield session

@pytest.fixture(name="client")
def client_fixture(session: Session):
    def get_session_override():
        return session

    app.dependency_overrides[get_session] = get_session_override
    client = TestClient(app)
    yield client
    app.dependency_overrides.clear()

@pytest.fixture(name="test_user_token")
def test_user_token_fixture(client: TestClient):
    # Create a user
    client.post("/auth/register", json={
        "email": "test@example.com",
        "password": "password123",
        "username": "testuser"
    })
    
    # Login to get token
    response = client.post("/auth/token", data={
        "username": "test@example.com",
        "password": "password123"
    })
    token = response.json()["access_token"]
    return token
