"""Tests for exchanges API endpoints."""

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

from backend.main import app
from src.core.database import Exchange


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


@pytest.fixture
def mock_exchange():
    """Mock exchange object."""
    exchange = Mock(spec=Exchange)
    exchange.id = 1
    exchange.name = "coinbase"
    exchange.is_enabled = True
    exchange.api_permissions = "read_only"
    return exchange


class TestListExchanges:
    """Tests for GET /api/exchanges."""
    
    @patch('backend.api.exchanges.get_db')
    def test_list_exchanges_success(self, mock_get_db, client):
        """Test listing exchanges."""
        mock_db = Mock()
        mock_session = Mock()
        mock_db.get_session.return_value = mock_session
        mock_get_db.return_value = mock_db
        
        mock_session.query.return_value.all.return_value = []
        
        response = client.get("/api/exchanges")
        
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)


class TestGetExchange:
    """Tests for GET /api/exchanges/{exchange_id}."""
    
    @patch('backend.api.exchanges.get_db')
    def test_get_exchange_success(self, mock_get_db, client, mock_exchange):
        """Test getting exchange by ID."""
        mock_db = Mock()
        mock_session = Mock()
        mock_db.get_session.return_value = mock_session
        mock_get_db.return_value = mock_db
        
        mock_session.query.return_value.filter_by.return_value.first.return_value = mock_exchange
        
        response = client.get("/api/exchanges/1")
        
        assert response.status_code == 200
        data = response.json()
        assert data["id"] == 1
    
    @patch('backend.api.exchanges.get_db')
    def test_get_exchange_not_found(self, mock_get_db, client):
        """Test getting non-existent exchange."""
        mock_db = Mock()
        mock_session = Mock()
        mock_db.get_session.return_value = mock_session
        mock_get_db.return_value = mock_db
        
        mock_session.query.return_value.filter_by.return_value.first.return_value = None
        
        response = client.get("/api/exchanges/999")
        
        assert response.status_code == 404
        assert "Exchange not found" in response.json()["detail"]

