import express from 'express';
import { generateTradePlan, formatTradePlan } from '../services/tradePlanGenerator.js';
import { rawQuery } from '../db.js';

const router = express.Router();

/**
 * POST /api/trade-plans/generate
 * Generate a trade plan for a signal
 */
router.post('/generate', async (req, res) => {
  try {
    const { signalData, priceData, options } = req.body;
    
    if (!signalData) {
      return res.status(400).json({
        success: false,
        error: 'signalData is required'
      });
    }
    
    // Get current price if not provided
    let priceContext = priceData;
    if (!priceContext || !priceContext.close) {
      const symbol = signalData.Symbol || signalData.symbol_norm || signalData.ticker;
      if (symbol) {
        const priceQuery = `
          SELECT close, high, low, volume, ts
          FROM public.prices_intraday_1m
          WHERE UPPER(symbol) = UPPER($1)
          ORDER BY ts DESC
          LIMIT 1
        `;
        const priceResult = await rawQuery(priceQuery, [symbol]);
        if (priceResult && priceResult[0]) {
          priceContext = {
            close: parseFloat(priceResult[0].close),
            high: parseFloat(priceResult[0].high),
            low: parseFloat(priceResult[0].low),
            volume: parseFloat(priceResult[0].volume)
          };
        }
      }
    }
    
    const tradePlan = generateTradePlan(signalData, priceContext, options);
    const formatted = formatTradePlan(tradePlan);
    
    res.json({
      success: true,
      tradePlan: formatted,
      raw: tradePlan
    });
    
  } catch (error) {
    console.error('Trade plan generation error:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

export default router;

