/**
 * Trading Routes
 * Market data, paper trading, and watchlist endpoints
 */

import { Router, RequestHandler } from 'express';
import * as tradingController from './controllers/trading.controller';
import * as watchlistController from './controllers/watchlist.controller';
import * as indicatorsController from './controllers/indicators.controller';
import * as alertsController from './controllers/alerts.controller';
import { requireAuth } from '../../core/guards/auth.guard';

const router = Router();

// Type cast helper for authenticated routes
const authHandler = (fn: Function): RequestHandler => fn as RequestHandler;

// ============================================================================
// Market Data Routes (Public)
// ============================================================================

/**
 * GET /api/v1/trading/market/klines/:symbol
 * Get candlestick/kline data for a symbol
 * Query params: interval, startTime, endTime, limit
 */
router.get('/market/klines/:symbol', tradingController.getKlines);

/**
 * GET /api/v1/trading/market/price/:symbol
 * Get current price for a symbol
 */
router.get('/market/price/:symbol', tradingController.getPrice);

/**
 * GET /api/v1/trading/market/prices
 * Get prices for multiple symbols
 * Query params: symbols (comma-separated)
 */
router.get('/market/prices', tradingController.getPrices);

/**
 * GET /api/v1/trading/market/ticker/:symbol
 * Get 24h ticker for a symbol
 */
router.get('/market/ticker/:symbol', tradingController.getTicker);

/**
 * GET /api/v1/trading/market/tickers
 * Get tickers for multiple symbols
 * Query params: symbols (comma-separated)
 */
router.get('/market/tickers', tradingController.getTickers);

/**
 * GET /api/v1/trading/market/orderbook/:symbol
 * Get order book for a symbol
 * Query params: limit
 */
router.get('/market/orderbook/:symbol', tradingController.getOrderBook);

/**
 * GET /api/v1/trading/market/search
 * Search for symbols
 * Query params: query, limit
 */
router.get('/market/search', tradingController.searchSymbols);

/**
 * GET /api/v1/trading/market/popular
 * Get popular trading pairs with tickers
 */
router.get('/market/popular', tradingController.getPopularSymbols);

/**
 * GET /api/v1/trading/market/watchlist
 * Get watchlist data for symbols
 * Query params: symbols (comma-separated, required)
 */
router.get('/market/watchlist', tradingController.getWatchlist);

// ============================================================================
// Technical Indicators Routes (Public)
// ============================================================================

/**
 * GET /api/v1/trading/indicators/:symbol/sma
 * Get Simple Moving Average
 * Query params: interval, period (default 20), limit
 */
router.get('/indicators/:symbol/sma', indicatorsController.getSMA);

/**
 * GET /api/v1/trading/indicators/:symbol/ema
 * Get Exponential Moving Average
 * Query params: interval, period (default 20), limit
 */
router.get('/indicators/:symbol/ema', indicatorsController.getEMA);

/**
 * GET /api/v1/trading/indicators/:symbol/rsi
 * Get Relative Strength Index
 * Query params: interval, period (default 14), limit
 */
router.get('/indicators/:symbol/rsi', indicatorsController.getRSI);

/**
 * GET /api/v1/trading/indicators/:symbol/macd
 * Get MACD
 * Query params: interval, fastPeriod (12), slowPeriod (26), signalPeriod (9), limit
 */
router.get('/indicators/:symbol/macd', indicatorsController.getMACD);

/**
 * GET /api/v1/trading/indicators/:symbol/stochastic
 * Get Stochastic Oscillator
 * Query params: interval, kPeriod (14), dPeriod (3), smoothK (3), limit
 */
router.get('/indicators/:symbol/stochastic', indicatorsController.getStochastic);

/**
 * GET /api/v1/trading/indicators/:symbol/bollinger
 * Get Bollinger Bands
 * Query params: interval, period (20), stdDev (2), limit
 */
router.get('/indicators/:symbol/bollinger', indicatorsController.getBollingerBands);

/**
 * GET /api/v1/trading/indicators/:symbol/atr
 * Get Average True Range
 * Query params: interval, period (14), limit
 */
router.get('/indicators/:symbol/atr', indicatorsController.getATR);

/**
 * GET /api/v1/trading/indicators/:symbol/vwap
 * Get Volume Weighted Average Price
 * Query params: interval, limit
 */
router.get('/indicators/:symbol/vwap', indicatorsController.getVWAP);

/**
 * GET /api/v1/trading/indicators/:symbol/all
 * Get all common indicators at once
 * Query params: interval, limit
 */
router.get('/indicators/:symbol/all', indicatorsController.getAllIndicators);

// ============================================================================
// Paper Trading Routes (Authenticated)
// TODO: Add authentication middleware
// ============================================================================

/**
 * POST /api/v1/trading/paper/initialize
 * Initialize paper trading account
 * Body: { initialCapital?: number }
 */
router.post('/paper/initialize', authHandler(tradingController.initializePaperAccount));

/**
 * GET /api/v1/trading/paper/balances
 * Get paper trading balances
 */
router.get('/paper/balances', authHandler(tradingController.getPaperBalances));

/**
 * POST /api/v1/trading/paper/orders
 * Create a paper trading order
 * Body: CreateOrderInput
 */
router.post('/paper/orders', authHandler(tradingController.createPaperOrder));

/**
 * DELETE /api/v1/trading/paper/orders/:orderId
 * Cancel a paper trading order
 */
router.delete('/paper/orders/:orderId', authHandler(tradingController.cancelPaperOrder));

/**
 * GET /api/v1/trading/paper/orders
 * Get paper trading orders
 * Query params: status, symbol, limit
 */
router.get('/paper/orders', authHandler(tradingController.getPaperOrders));

/**
 * GET /api/v1/trading/paper/positions
 * Get paper trading positions
 * Query params: status, symbol
 */
router.get('/paper/positions', authHandler(tradingController.getPaperPositions));

/**
 * POST /api/v1/trading/paper/positions/:positionId/close
 * Close a paper trading position
 * Body: { quantity?: number }
 */
router.post('/paper/positions/:positionId/close', authHandler(tradingController.closePaperPosition));

/**
 * GET /api/v1/trading/paper/trades
 * Get paper trading trades history
 * Query params: symbol, limit, startTime, endTime
 */
router.get('/paper/trades', authHandler(tradingController.getPaperTrades));

/**
 * GET /api/v1/trading/paper/portfolio
 * Get paper trading portfolio summary
 */
router.get('/paper/portfolio', authHandler(tradingController.getPaperPortfolio));

/**
 * POST /api/v1/trading/paper/reset
 * Reset paper trading account
 */
router.post('/paper/reset', authHandler(tradingController.resetPaperAccount));

/**
 * GET /api/v1/trading/paper/settings
 * Get paper trading settings
 */
router.get('/paper/settings', authHandler(tradingController.getPaperSettings));

/**
 * PATCH /api/v1/trading/paper/settings
 * Update paper trading settings
 * Body: Partial<PaperSettings>
 */
router.patch('/paper/settings', authHandler(tradingController.updatePaperSettings));

/**
 * GET /api/v1/trading/paper/stats
 * Get paper trading performance statistics
 * Query params: accountId
 */
router.get('/paper/stats', authHandler(tradingController.getPaperStats));

// ============================================================================
// Watchlist Routes (Authenticated)
// ============================================================================

/**
 * GET /api/v1/trading/watchlists
 * Get all user's watchlists
 */
router.get('/watchlists', authHandler(watchlistController.getUserWatchlists));

/**
 * GET /api/v1/trading/watchlists/default
 * Get user's default watchlist
 */
router.get('/watchlists/default', authHandler(watchlistController.getDefaultWatchlist));

/**
 * GET /api/v1/trading/watchlists/:watchlistId
 * Get a single watchlist with items
 */
router.get('/watchlists/:watchlistId', authHandler(watchlistController.getWatchlist));

/**
 * POST /api/v1/trading/watchlists
 * Create a new watchlist
 * Body: CreateWatchlistInput
 */
router.post('/watchlists', authHandler(watchlistController.createWatchlist));

/**
 * PATCH /api/v1/trading/watchlists/:watchlistId
 * Update a watchlist
 * Body: UpdateWatchlistInput
 */
router.patch('/watchlists/:watchlistId', authHandler(watchlistController.updateWatchlist));

/**
 * DELETE /api/v1/trading/watchlists/:watchlistId
 * Delete a watchlist
 */
router.delete('/watchlists/:watchlistId', authHandler(watchlistController.deleteWatchlist));

/**
 * POST /api/v1/trading/watchlists/:watchlistId/symbols
 * Add a symbol to a watchlist
 * Body: AddSymbolInput
 */
router.post('/watchlists/:watchlistId/symbols', authHandler(watchlistController.addSymbol));

/**
 * PATCH /api/v1/trading/watchlists/:watchlistId/symbols/:symbol
 * Update a symbol in a watchlist
 * Body: UpdateSymbolInput
 */
router.patch('/watchlists/:watchlistId/symbols/:symbol', authHandler(watchlistController.updateSymbol));

/**
 * DELETE /api/v1/trading/watchlists/:watchlistId/symbols/:symbol
 * Remove a symbol from a watchlist
 */
router.delete('/watchlists/:watchlistId/symbols/:symbol', authHandler(watchlistController.removeSymbol));

/**
 * POST /api/v1/trading/watchlists/:watchlistId/reorder
 * Reorder symbols in a watchlist
 * Body: { symbolOrder: string[] }
 */
router.post('/watchlists/:watchlistId/reorder', authHandler(watchlistController.reorderSymbols));

// ============================================================================
// Price Alerts Routes (Authenticated)
// ============================================================================

/**
 * GET /api/v1/trading/alerts
 * Get user's price alerts
 * Query: status, symbol, alertType
 */
router.get('/alerts', authHandler(requireAuth), authHandler(alertsController.getAlerts));

/**
 * GET /api/v1/trading/alerts/stats
 * Get alert statistics
 */
router.get('/alerts/stats', authHandler(requireAuth), authHandler(alertsController.getAlertStats));

/**
 * GET /api/v1/trading/alerts/:alertId
 * Get a specific alert
 */
router.get('/alerts/:alertId', authHandler(requireAuth), authHandler(alertsController.getAlertById));

/**
 * POST /api/v1/trading/alerts
 * Create a new price alert
 * Body: { symbol, alertType, targetPrice, percentThreshold?, notificationChannels?, message?, expiresAt? }
 */
router.post('/alerts', authHandler(requireAuth), authHandler(alertsController.createAlert));

/**
 * PATCH /api/v1/trading/alerts/:alertId
 * Update an alert
 * Body: { targetPrice?, percentThreshold?, notificationChannels?, message?, expiresAt?, status? }
 */
router.patch('/alerts/:alertId', authHandler(requireAuth), authHandler(alertsController.updateAlert));

/**
 * DELETE /api/v1/trading/alerts/:alertId
 * Delete an alert
 */
router.delete('/alerts/:alertId', authHandler(requireAuth), authHandler(alertsController.deleteAlert));

/**
 * POST /api/v1/trading/alerts/:alertId/enable
 * Enable an alert
 */
router.post('/alerts/:alertId/enable', authHandler(requireAuth), authHandler(alertsController.enableAlert));

/**
 * POST /api/v1/trading/alerts/:alertId/disable
 * Disable an alert
 */
router.post('/alerts/:alertId/disable', authHandler(requireAuth), authHandler(alertsController.disableAlert));

export { router as tradingRouter };
