"""Tests for database system."""

import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from src.core.database import (
    get_database, Base, Exchange, Strategy, Trade, Position, Order
)


class TestDatabase:
    """Tests for database operations."""
    
    def test_database_initialization(self):
        """Test database initialization."""
        db = get_database()
        assert db is not None
        assert db.engine is not None
    
    def test_table_creation(self, mock_database):
        """Test table creation."""
        engine, Session = mock_database
        # Verify tables exist
        assert Base.metadata.tables.get('exchanges') is not None
        assert Base.metadata.tables.get('strategies') is not None
        assert Base.metadata.tables.get('trades') is not None
    
    def test_exchange_model(self, mock_database):
        """Test Exchange model."""
        engine, Session = mock_database
        session = Session()
        
        exchange = Exchange(
            name="test_exchange",
            api_key="encrypted_key",
            secret_key="encrypted_secret",
            api_permissions="read_only",
            is_enabled=True
        )
        session.add(exchange)
        session.commit()
        
        retrieved = session.query(Exchange).filter_by(name="test_exchange").first()
        assert retrieved is not None
        assert retrieved.name == "test_exchange"
        assert retrieved.api_permissions == "read_only"
        
        session.close()
    
    def test_strategy_model(self, mock_database):
        """Test Strategy model."""
        engine, Session = mock_database
        session = Session()
        
        strategy = Strategy(
            name="test_strategy",
            strategy_type="RSI",
            parameters='{"rsi_period": 14}',
            is_enabled=True,
            is_paper_trading=True
        )
        session.add(strategy)
        session.commit()
        
        retrieved = session.query(Strategy).filter_by(name="test_strategy").first()
        assert retrieved is not None
        assert retrieved.strategy_type == "RSI"
        
        session.close()
    
    def test_trade_model(self, mock_database):
        """Test Trade model."""
        engine, Session = mock_database
        session = Session()
        
        trade = Trade(
            order_id="test_order_123",
            symbol="BTC/USD",
            side="buy",
            type="market",
            price=50000.0,
            amount=0.01,
            cost=500.0,
            fee=0.5,
            status="filled",
            is_paper_trade=True
        )
        session.add(trade)
        session.commit()
        
        retrieved = session.query(Trade).filter_by(order_id="test_order_123").first()
        assert retrieved is not None
        assert retrieved.symbol == "BTC/USD"
        assert retrieved.status == "filled"
        
        session.close()

