"""Integration tests for API workflows."""

import pytest
from fastapi.testclient import TestClient
from unittest.mock import patch, Mock

from backend.main import app


@pytest.fixture
def client():
    """Test client fixture."""
    return TestClient(app)


@pytest.mark.integration
class TestTradingWorkflow:
    """Test complete trading workflow through API."""
    
    @patch('backend.api.trading.get_trading_engine')
    @patch('backend.api.trading.get_db')
    def test_complete_trading_workflow(self, mock_get_db, mock_get_engine, client):
        """Test: Place order → Check order status → Get positions."""
        # Setup mocks
        mock_engine = Mock()
        mock_order = Mock()
        mock_order.id = 1
        mock_order.symbol = "BTC/USD"
        mock_order.side = "buy"
        mock_order.status = "filled"
        mock_engine.execute_order.return_value = mock_order
        mock_get_engine.return_value = mock_engine
        
        mock_db = Mock()
        mock_session = Mock()
        mock_db.get_session.return_value = mock_session
        mock_get_db.return_value = mock_db
        
        # Mock order query
        mock_session.query.return_value.filter_by.return_value.order_by.return_value.limit.return_value.all.return_value = [mock_order]
        mock_session.query.return_value.filter_by.return_value.first.return_value = mock_order
        
        # Place order
        order_data = {
            "exchange_id": 1,
            "symbol": "BTC/USD",
            "side": "buy",
            "order_type": "market",
            "quantity": "0.1",
            "paper_trading": True
        }
        create_response = client.post("/api/trading/orders", json=order_data)
        assert create_response.status_code == 200
        
        order_id = create_response.json()["id"]
        
        # Get order status
        status_response = client.get(f"/api/trading/orders/{order_id}")
        assert status_response.status_code == 200
        assert status_response.json()["id"] == order_id
        
        # Get orders list
        orders_response = client.get("/api/trading/orders")
        assert orders_response.status_code == 200
        assert isinstance(orders_response.json(), list)


@pytest.mark.integration
class TestPortfolioWorkflow:
    """Test portfolio workflow through API."""
    
    @patch('backend.api.portfolio.get_portfolio_tracker')
    def test_portfolio_workflow(self, mock_get_tracker, client):
        """Test: Get current portfolio → Get portfolio history."""
        mock_tracker = Mock()
        mock_tracker.get_current_portfolio.return_value = {
            "positions": [],
            "performance": {"total_return": 0.1},
            "timestamp": "2025-01-01T00:00:00"
        }
        mock_tracker.get_portfolio_history.return_value = [
            {"timestamp": "2025-01-01T00:00:00", "total_value": 1000.0, "total_pnl": 0.0}
        ]
        mock_get_tracker.return_value = mock_tracker
        
        # Get current portfolio
        current_response = client.get("/api/portfolio/current?paper_trading=true")
        assert current_response.status_code == 200
        assert "positions" in current_response.json()
        
        # Get portfolio history
        history_response = client.get("/api/portfolio/history?paper_trading=true&days=30")
        assert history_response.status_code == 200
        assert "dates" in history_response.json()

