import sys
import os
from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient

# Ensure "import main" works when running pytest from the backend/ folder
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import main


@pytest.fixture
def mock_db():
    """
    Replaces main.get_db() with a fake connection/cursor so tests never
    touch the real PostgreSQL instance on k3. Each test configures
    fetchone()/fetchall() return values as needed for its scenario.
    """
    fake_cursor = MagicMock()
    fake_conn = MagicMock()
    fake_conn.cursor.return_value = fake_cursor

    with patch("main.get_db", return_value=fake_conn):
        yield fake_cursor


@pytest.fixture
def client(mock_db):
    """
    TestClient used as a context manager so startup events (table creation
    queries) run against the mocked DB instead of the real one.
    """
    with TestClient(main.app) as c:
        yield c


@pytest.fixture
def auth_token():
    """
    Injects a valid token directly into the app's in-memory token store,
    bypassing the /api/login flow for tests that only need an authorized session.
    """
    token = "test-token-123"
    main.active_tokens.add(token)
    yield token
    main.active_tokens.discard(token)
