import express from 'express';
import { batchFetchYahooFinanceData } from '../services/yahooFinanceService.js';
import { fetchVolumeHistoryBulk } from '../services/volumeHistoryService.js';

const router = express.Router();

/**
 * GET /api/stock-prices
 * Fetch stock prices and volume history for multiple symbols
 * Query params: symbols (comma-separated list)
 */
router.get('/', async (req, res) => {
  try {
    const { symbols } = req.query;
    
    if (!symbols) {
      return res.status(400).json({
        success: false,
        error: 'symbols parameter is required (comma-separated list)'
      });
    }

    const symbolList = symbols.split(',').map(s => s.trim().toUpperCase()).filter(Boolean);
    
    if (symbolList.length === 0) {
      return res.json({
        success: true,
        data: {}
      });
    }

    console.log(`📈 Fetching stock prices and volume for ${symbolList.length} symbols...`);
    
    let stockPrices = {};
    let volumeHistory = {};
    
    // Fetch from Yahoo Finance
    try {
      stockPrices = await batchFetchYahooFinanceData(symbolList, 5);
      console.log(`✅ Successfully fetched stock prices for ${Object.keys(stockPrices).length} symbols`);
      
      // Extract volume history from stock price data
      Object.keys(stockPrices).forEach(symbol => {
        const priceData = stockPrices[symbol];
        if (priceData && priceData.volumeHistory && priceData.volumeHistory.length > 0) {
          volumeHistory[symbol] = priceData.volumeHistory;
        }
      });
      console.log(`✅ Extracted volume history for ${Object.keys(volumeHistory).length} symbols`);
    } catch (error) {
      console.warn('⚠️ Error fetching stock prices from Yahoo Finance:', error.message);
    }

    // Fallback: Fetch volume history from database for symbols that didn't get data from Yahoo Finance
    const missingSymbols = symbolList.filter(s => !volumeHistory[s]);
    if (missingSymbols.length > 0) {
      console.log(`📊 Fetching volume history from database for ${missingSymbols.length} symbols...`);
      try {
        const dbVolumeHistory = await fetchVolumeHistoryBulk(missingSymbols);
        // Merge database results
        Object.keys(dbVolumeHistory).forEach(symbol => {
          if (!volumeHistory[symbol] && dbVolumeHistory[symbol].length > 0) {
            volumeHistory[symbol] = dbVolumeHistory[symbol];
          }
        });
        console.log(`✅ Fetched volume history from database for ${Object.keys(dbVolumeHistory).length} additional symbols`);
      } catch (error) {
        console.warn('⚠️ Error fetching volume history from database:', error.message);
      }
    }

    // Combine stock prices and volume history
    const result = {};
    symbolList.forEach(symbol => {
      result[symbol] = {
        stockPrice: stockPrices[symbol] || null,
        volumeHistory: volumeHistory[symbol] || []
      };
    });

    res.json({
      success: true,
      data: result,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('Stock prices error:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

export default router;

