-- Insert initial reference data

-- Insert common symbols
INSERT INTO trading.symbols (symbol, name, exchange, asset_type, sector) VALUES
('AAPL', 'Apple Inc.', 'NASDAQ', 'equity', 'Technology'),
('GOOGL', 'Alphabet Inc.', 'NASDAQ', 'equity', 'Technology'),
('MSFT', 'Microsoft Corporation', 'NASDAQ', 'equity', 'Technology'),
('AMZN', 'Amazon.com Inc.', 'NASDAQ', 'equity', 'Consumer Discretionary'),
('TSLA', 'Tesla Inc.', 'NASDAQ', 'equity', 'Consumer Discretionary'),
('NVDA', 'NVIDIA Corporation', 'NASDAQ', 'equity', 'Technology'),
('META', 'Meta Platforms Inc.', 'NASDAQ', 'equity', 'Technology'),
('NFLX', 'Netflix Inc.', 'NASDAQ', 'equity', 'Communication Services'),
('SPY', 'SPDR S&P 500 ETF Trust', 'NYSE', 'etf', 'Broad Market'),
('QQQ', 'Invesco QQQ Trust', 'NASDAQ', 'etf', 'Technology'),
('BTC-USD', 'Bitcoin USD', 'CRYPTO', 'cryptocurrency', 'Digital Assets'),
('ETH-USD', 'Ethereum USD', 'CRYPTO', 'cryptocurrency', 'Digital Assets');

-- Insert default trading account
INSERT INTO trading.accounts (name, account_type, broker, cash_balance, buying_power, total_value) VALUES
('Demo Account', 'paper', 'demo', 100000.00, 100000.00, 100000.00);

-- Insert demo strategy
INSERT INTO strategy.strategies (name, description, config, parameters, is_active) VALUES
('Demo Mean Reversion', 'Simple mean reversion strategy for demonstration', 
 '{"timeframe": "1h", "lookback_period": 20}',
 '{"rsi_oversold": 30, "rsi_overbought": 70, "position_size": 0.1}',
 false);

-- Insert basic risk limits
INSERT INTO risk.limits (strategy_id, limit_type, limit_value, threshold_warning) 
SELECT s.id, 'max_position_size', 10000.00, 8000.00
FROM strategy.strategies s 
WHERE s.name = 'Demo Mean Reversion';

INSERT INTO risk.limits (strategy_id, limit_type, limit_value, threshold_warning)
SELECT s.id, 'max_daily_loss', 5000.00, 4000.00
FROM strategy.strategies s 
WHERE s.name = 'Demo Mean Reversion';

-- Create updated_at trigger function
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

-- Apply updated_at triggers
CREATE TRIGGER update_symbols_updated_at BEFORE UPDATE ON trading.symbols FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_orders_updated_at BEFORE UPDATE ON trading.orders FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_positions_updated_at BEFORE UPDATE ON trading.positions FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_accounts_updated_at BEFORE UPDATE ON trading.accounts FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_strategies_updated_at BEFORE UPDATE ON strategy.strategies FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TRIGGER update_limits_updated_at BEFORE UPDATE ON risk.limits FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
