← back to Wine Finder Next

app/api/price-history/route.ts

74 lines

import { NextRequest, NextResponse } from 'next/server'

const priceHistoryService = require('@/lib/services/priceHistoryService')

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const wineName = searchParams.get('wine')
  const vintage = searchParams.get('vintage')
  const wineId = searchParams.get('wineId') // New parameter for arbitrage UI

  try {
    // Support both old format (wine + vintage) and new format (wineId)
    let queryName = wineName
    let queryVintage = vintage

    if (wineId && !wineName) {
      // Parse wineId format: "source-name-vintage"
      const parts = wineId.split('-')
      if (parts.length >= 2) {
        queryName = parts.slice(1, -1).join('-') // Everything except source and vintage
        queryVintage = parts[parts.length - 1] === 'nv' ? null : parts[parts.length - 1]
      }
    }

    if (!queryName) {
      return NextResponse.json({ error: 'Wine name or wineId is required' }, { status: 400 })
    }

    const history = await priceHistoryService.getPriceHistory(queryName, queryVintage)

    if (!history.success || !history.pricePoints || history.pricePoints.length === 0) {
      return NextResponse.json({
        wine: queryName,
        vintage: queryVintage,
        success: false,
        error: 'No historical price data available for this wine',
        history: [], // New format for arbitrage UI
        pricePoints: [],
        stats: null
      })
    }

    const chartData = priceHistoryService.generateChartData(history.pricePoints)

    // Transform to new format for arbitrage UI
    const historyPoints = chartData.map((point: any) => ({
      timestamp: point.timestamp,
      price: point.price,
      source: point.source || 'unknown'
    }))

    return NextResponse.json({
      wine: queryName,
      vintage: queryVintage,
      success: true,
      history: historyPoints, // New format for arbitrage UI
      pricePoints: chartData, // Old format for backward compatibility
      stats: history.stats
    })
  } catch (error: any) {
    console.error('Price history error:', error)
    return NextResponse.json({
      wine: wineName,
      vintage,
      success: false,
      error: 'Failed to fetch price history',
      message: error.message,
      history: [], // New format
      pricePoints: [],
      stats: null
    }, { status: 500 })
  }
}