import express from 'express';
import { rawQuery } from '../db.js';
import { calculateSupportResistance, calculatePricePositioning } from '../services/supportResistanceCalculator.js';

const router = express.Router();

/**
 * GET /api/prices?symbols=AAPL,TSLA,MSFT
 * Get current prices for multiple symbols (for watchlist)
 */
router.get('/', async (req, res) => {
  try {
    const { symbols } = req.query;
    
    if (!symbols) {
      return res.json({ success: true, data: [] });
    }

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

    // Get latest price for each symbol from the most recent table
    const query = `
      WITH latest_prices AS (
        SELECT DISTINCT ON (UPPER(COALESCE(symbol, "Symbol", Ticker, ticker)))
          UPPER(COALESCE(symbol, "Symbol", Ticker, ticker)) AS symbol,
          close AS price,
          ts,
          (close - LAG(close) OVER (PARTITION BY UPPER(COALESCE(symbol, "Symbol", Ticker, ticker)) ORDER BY ts)) / NULLIF(LAG(close) OVER (PARTITION BY UPPER(COALESCE(symbol, "Symbol", Ticker, ticker)) ORDER BY ts), 0) * 100 AS change_percent
        FROM prices_intraday_1m
        WHERE UPPER(COALESCE(symbol, "Symbol", Ticker, ticker)) = ANY($1)
          AND ts >= NOW() - INTERVAL '1 day'
        ORDER BY UPPER(COALESCE(symbol, "Symbol", Ticker, ticker)), ts DESC
      )
      SELECT 
        symbol,
        price,
        COALESCE(change_percent, 0) AS change_percent,
        COALESCE(change_percent, 0) AS change
      FROM latest_prices
      ORDER BY symbol
    `;

    const data = await rawQuery(query, [symbolList]);

    res.json({
      success: true,
      data: Array.isArray(data) ? data.map(row => ({
        symbol: row.symbol,
        price: parseFloat(row.price || 0),
        change: parseFloat(row.change || 0),
        changePercent: parseFloat(row.change_percent || 0)
      })) : []
    });

  } catch (error) {
    console.error('Multi-symbol price error:', error);
    res.status(500).json({ 
      success: false, 
      error: error.message,
      data: []
    });
  }
});

router.get('/:symbol', async (req, res) => {
  try {
    const { symbol } = req.params;
    const { timeframe = '1m', lookback = 1, startDate, endDate } = req.query;

    // Map timeframe to table name (whitelist for security)
    const tableMap = {
      '1m': 'prices_intraday_1m',
      '5m': 'prices_intraday_5m',
      '15m': 'prices_intraday_15m',
      '1h': 'prices_intraday_1h',
      '1D': 'prices_daily'
    };

    const tableName = tableMap[timeframe] || 'prices_intraday_1m';
    const lookbackDays = Math.max(1, Math.min(30, parseInt(lookback) || 1)); // Clamp between 1-30 days

    // Build time condition
    let timeCondition = `ts >= NOW() - INTERVAL '${lookbackDays} day'`;
    if (startDate && endDate) {
      // Use date range if provided
      timeCondition = `ts >= '${startDate}'::timestamp AND ts <= '${endDate}'::timestamp + INTERVAL '1 day'`;
    } else if (startDate) {
      // Only start date provided
      timeCondition = `ts >= '${startDate}'::timestamp`;
    }

    // Build query with parameterized values
    // Handle both 'symbol' and 'Symbol' column names (PostgreSQL is case-insensitive for unquoted identifiers)
    const query = `
      SELECT
        ts,
        open,
        high,
        low,
        close,
        volume
      FROM ${tableName}
      WHERE UPPER(COALESCE(symbol, "Symbol", Ticker, ticker)) = UPPER($1)
        AND ${timeCondition}
      ORDER BY ts ASC
      LIMIT 1000
    `;

    const data = await rawQuery(query, [symbol]);

    if (!data || data.length === 0) {
      return res.json({ 
        success: true, 
        candles: [], 
        volume: [],
        message: 'No price data found for this symbol/timeframe'
      });
    }

    const candles = data.map(row => ({
      time: Math.floor(new Date(row.ts).getTime() / 1000),
      open: parseFloat(row.open),
      high: parseFloat(row.high),
      low: parseFloat(row.low),
      close: parseFloat(row.close),
    }));

    const volume = data.map(row => ({
      time: Math.floor(new Date(row.ts).getTime() / 1000),
      value: parseFloat(row.volume),
      color: row.close >= row.open ? '#22c55e40' : '#ef444440',
    }));

    res.json({ 
      success: true, 
      candles, 
      volume,
      dateRange: startDate && endDate ? { startDate, endDate } : null
    });

  } catch (error) {
    console.error('Price data error:', error);
    res.status(500).json({ 
      success: false, 
      error: error.message,
      candles: [],
      volume: []
    });
  }
});

export default router;

