← back to Wine Finder Next
app/api/real-history/route.ts
60 lines
import { NextRequest, NextResponse } from 'next/server';
import { getRealPriceHistory, getLastSaleInfo, getAveragePriceBySource } from '@/lib/services/realHistoryService';
/**
* Real Price History API
* Returns actual tracked prices from JSONL data
*/
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const wineName = searchParams.get('wine');
if (!wineName) {
return NextResponse.json({ error: 'Wine name is required' }, { status: 400 });
}
try {
const [history, lastSale, averages] = await Promise.all([
getRealPriceHistory(wineName),
getLastSaleInfo(wineName),
getAveragePriceBySource(wineName),
]);
// Transform for recharts format
const chartData = history.map(point => ({
timestamp: new Date(point.timestamp).toLocaleDateString(),
price: point.price,
source: point.source,
fullDate: point.timestamp,
}));
// Calculate price stats
const prices = history.map(h => h.price);
const stats = prices.length > 0 ? {
current: prices[prices.length - 1],
min: Math.min(...prices),
max: Math.max(...prices),
avg: prices.reduce((sum, p) => sum + p, 0) / prices.length,
totalDataPoints: prices.length,
} : null;
return NextResponse.json({
success: true,
wine: wineName,
history: chartData,
lastSale,
averagesBySource: averages,
stats,
dataPoints: history.length,
});
} catch (error: any) {
console.error('Real history error:', error);
return NextResponse.json({
success: false,
error: 'Failed to fetch real price history',
message: error.message,
}, { status: 500 });
}
}