← back to Wine Finder Next

app/api/ingest/winebid/route.ts

90 lines

// app/api/ingest/winebid/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { auctions } = body;

    if (!Array.isArray(auctions)) {
      return NextResponse.json({ error: 'auctions array required' }, { status: 400 });
    }

    const db = getDb();
    const insertWine = db.prepare(`
      INSERT OR REPLACE INTO wines (
        name, varietal, vintage, region, country, 
        tasting_notes, winebid_id, image_url
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `);

    const insertPrice = db.prepare(`
      INSERT INTO wine_prices (wine_id, vendor, price, collected_at, product_id, metadata)
      VALUES (?, 'winebid', ?, datetime('now'), ?, ?)
    `);

    let processed = 0;
    let errors = 0;

    for (const auction of auctions) {
      try {
        // Insert or update wine
        const wineResult = insertWine.run(
          auction.wine_name || auction.title || '',
          auction.varietal || null,
          auction.vintage || null,
          auction.region || null,
          auction.country || null,
          auction.description || null,
          auction.lot_id || auction.winebid_id || null,
          auction.image_url || null
        );

        // Insert auction price data
        if (auction.current_bid || auction.final_price) {
          const price = auction.final_price || auction.current_bid;
          const metadata = {
            auction_end: auction.auction_end,
            lot_size: auction.lot_size,
            estimate_low: auction.estimate_low,
            estimate_high: auction.estimate_high,
            bid_count: auction.bid_count,
            is_final: !!auction.final_price
          };

          insertPrice.run(
            wineResult.lastInsertRowid,
            price,
            auction.lot_id || auction.winebid_id,
            JSON.stringify(metadata)
          );
        }

        processed++;
      } catch (error) {
        console.error('Error processing auction:', error);
        errors++;
      }
    }

    return NextResponse.json({
      success: true,
      processed,
      errors,
      message: `Processed ${processed} auction records from WineBid`
    });

  } catch (error) {
    console.error('WineBid ingest error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

export async function GET() {
  // Health check endpoint
  return NextResponse.json({ 
    status: 'WineBid ingest endpoint ready',
    timestamp: new Date().toISOString()
  });
}