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

# Add the parent directory to sys.path so we can import internal modules
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Mock the database and session modules BEFORE importing the app
mock_db = MagicMock()
mock_session = MagicMock()
mock_audit = MagicMock()
from unittest.mock import AsyncMock
mock_audit.log = AsyncMock()

mock_rate_limit = MagicMock()
mock_rate_limit.is_order_flooding.return_value = False

# Mapping of module names to their mocks
mocks = {
    "db": mock_db,
    "backend.db": mock_db,
    "session_utils": mock_session,
    "backend.session_utils": mock_session,
    "services.audit_service": MagicMock(audit_service=mock_audit),
    "backend.services.audit_service": MagicMock(audit_service=mock_audit),
    "services.rate_limit_service": MagicMock(rate_limit_service=mock_rate_limit),
    "backend.services.rate_limit_service": MagicMock(rate_limit_service=mock_rate_limit),
}

for mod_name, mock_obj in mocks.items():
    sys.modules[mod_name] = mock_obj

# Configuration to bypass real Redis/DB
mock_session.create_session.return_value = "mock-session-id"
mock_session.validate_session.return_value = True

from main import app

@pytest.fixture
def client():
    """Test client for FastAPI app"""
    with TestClient(app) as c:
        yield c

@pytest.fixture
def db_mock():
    """Fixture to access the mocked db module"""
    return mock_db
