import { NextResponse } from 'next/server' import pool from '@/lib/db' // GET /api/drops/active - Get the earliest unfilled drop (not sold out) that has started export async function GET() { try { const now = new Date() // Get all drops ordered by start_time (or created_at if start_time is null) const [rows] = await pool.execute( 'SELECT * FROM drops ORDER BY COALESCE(start_time, created_at) ASC' ) const drops = rows as any[] // Find the first drop that's not fully sold out and has started for (const drop of drops) { // Check if drop has started (start_time is in the past or null) const startTime = drop.start_time ? new Date(drop.start_time) : new Date(drop.created_at) if (startTime > now) { // Drop hasn't started yet - return it with a flag indicating it's upcoming // Calculate fill (will be 0 for upcoming drops) const [salesRows] = await pool.execute( 'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?', [drop.id] ) const salesData = salesRows as any[] const totalFillInGrams = salesData[0]?.total_fill || 0 let fill = totalFillInGrams if (drop.unit === 'kg') { fill = totalFillInGrams / 1000 } return NextResponse.json({ ...drop, fill: fill, is_upcoming: true, start_time: drop.start_time || drop.created_at, }) } // Calculate fill from sales records // Sales are stored in grams, so we need to convert based on drop unit const [salesRows] = await pool.execute( 'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?', [drop.id] ) const salesData = salesRows as any[] const totalFillInGrams = salesData[0]?.total_fill || 0 // Convert fill to drop's unit for comparison let fill = totalFillInGrams if (drop.unit === 'kg') { fill = totalFillInGrams / 1000 } // Check if drop is not fully sold out if (fill < drop.size) { // Return drop with calculated fill return NextResponse.json({ ...drop, fill: fill, is_upcoming: false, start_time: drop.start_time || drop.created_at, }) } } // No active drops found return NextResponse.json(null) } catch (error) { console.error('Error fetching active drop:', error) return NextResponse.json( { error: 'Failed to fetch active drop' }, { status: 500 } ) } }