← back to Wine Finder

routes/history.js

102 lines

const express = require('express');
const router = express.Router();
const googleSheets = require('../services/googleSheets');

// Generate demo price history
function generateDemoHistory(wineName) {
  const history = [];
  const basePrice = 50 + Math.random() * 100;
  const now = new Date();

  for (let i = 6; i >= 0; i--) {
    const date = new Date(now);
    date.setMonth(date.getMonth() - i);

    const priceVariation = (Math.random() - 0.5) * 20;
    const price = Math.max(20, basePrice + priceVariation);

    history.push({
      timestamp: date.toISOString(),
      price: parseFloat(price.toFixed(2)),
      rating: 92 + Math.floor(Math.random() * 5)
    });
  }

  return history;
}

// Get price history for a specific wine
router.get('/wine', async (req, res) => {
  try {
    const { name } = req.query;

    if (!name || typeof name !== 'string') {
      return res.status(400).json({
        success: false,
        error: 'Wine name is required'
      });
    }

    let result = await googleSheets.getWineHistory(name);

    // If no history, generate demo data
    if (!result.success || result.history.length === 0) {
      console.log('No history found, generating demo data');
      const demoHistory = generateDemoHistory(name);
      result = {
        success: true,
        history: demoHistory
      };
    }

    // Process history data for charting
    const chartData = {
      labels: [],
      prices: [],
      ratings: []
    };

    result.history.forEach(entry => {
      const date = new Date(entry.timestamp);
      chartData.labels.push(date.toLocaleDateString());
      chartData.prices.push(entry.price);
      chartData.ratings.push(entry.rating || null);
    });

    res.json({
      success: true,
      wine: name,
      history: result.history,
      chartData
    });

  } catch (error) {
    console.error('History retrieval error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to retrieve history: ' + error.message
    });
  }
});

// Get all unique wines tracked
router.get('/wines', async (req, res) => {
  try {
    // This would require reading all data and extracting unique wine names
    // For now, return a simple response
    res.json({
      success: true,
      message: 'Use /history/wine?name=WINE_NAME to get specific wine history'
    });

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

module.exports = router;