← back to Wine Finder Next
app/api/price-history/[wineName]/route.ts
69 lines
import { NextRequest, NextResponse } from 'next/server'
const googleSheets = require('@/lib/services/googleSheets')
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ wineName: string }> }
) {
try {
const { wineName: wineNameParam } = await params
const wineName = decodeURIComponent(wineNameParam)
if (!wineName) {
return NextResponse.json(
{ error: 'Wine name is required' },
{ status: 400 }
)
}
// Get historical data from Google Sheets
const result = await googleSheets.getWineHistory(wineName)
if (!result.success) {
return NextResponse.json(
{ error: 'Failed to fetch price history', message: result.error },
{ status: 500 }
)
}
// Process data for charting
const history = result.history || []
// Group by date and source for better charting
const priceData = history.map((entry: any) => ({
date: new Date(entry.timestamp).toLocaleDateString(),
timestamp: entry.timestamp,
price: parseFloat(entry.price) || 0,
source: entry.source,
vintage: entry.vintage,
rating: entry.rating,
url: entry.url
}))
// Calculate price statistics
const prices = priceData.map((d: any) => d.price).filter((p: number) => p > 0)
const stats = prices.length > 0 ? {
min: Math.min(...prices),
max: Math.max(...prices),
avg: prices.reduce((a: number, b: number) => a + b, 0) / prices.length,
current: prices[prices.length - 1],
count: prices.length
} : null
return NextResponse.json({
wineName,
history: priceData,
stats,
total: priceData.length
})
} catch (error: any) {
console.error('Price history error:', error)
return NextResponse.json(
{ error: 'Failed to fetch price history', message: error.message },
{ status: 500 }
)
}
}