import { NextRequest, NextResponse } from 'next/server' import { cookies } from 'next/headers' import pool from '@/lib/db' // POST /api/sales - Create a new sale export async function POST(request: NextRequest) { try { // Get buyer_id from session cookie const cookieStore = await cookies() const buyerIdCookie = cookieStore.get('buyer_id')?.value if (!buyerIdCookie) { return NextResponse.json( { error: 'Authentication required. Please log in to make a purchase.' }, { status: 401 } ) } const buyer_id = parseInt(buyerIdCookie, 10) const body = await request.json() const { drop_id, size } = body // Validate required fields if (!drop_id || !size) { return NextResponse.json( { error: 'Missing required fields: drop_id, size' }, { status: 400 } ) } // Validate size is positive if (size <= 0) { return NextResponse.json( { error: 'Size must be greater than 0' }, { status: 400 } ) } // Check if drop exists and get its details const [dropRows] = await pool.execute( 'SELECT * FROM drops WHERE id = ?', [drop_id] ) const drops = dropRows as any[] if (drops.length === 0) { return NextResponse.json( { error: 'Drop not found' }, { status: 404 } ) } const drop = drops[0] // Calculate current fill from sales 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 currentFill = salesData[0]?.total_fill || 0 // Convert fill to the drop's unit for comparison let currentFillInDropUnit = currentFill let sizeInDropUnit = size if (drop.unit === 'kg') { // If drop unit is kg, convert sales (in grams) to kg currentFillInDropUnit = currentFill / 1000 sizeInDropUnit = size / 1000 } // Check if there's enough remaining inventory const remaining = drop.size - currentFillInDropUnit if (sizeInDropUnit > remaining) { return NextResponse.json( { error: 'Not enough inventory remaining' }, { status: 400 } ) } // Insert new sale const [result] = await pool.execute( 'INSERT INTO sales (drop_id, buyer_id, size) VALUES (?, ?, ?)', [drop_id, buyer_id, size] ) const insertId = (result as any).insertId // Fetch the created sale const [rows] = await pool.execute('SELECT * FROM sales WHERE id = ?', [ insertId, ]) const sales = rows as any[] return NextResponse.json(sales[0], { status: 201 }) } catch (error) { console.error('Error creating sale:', error) return NextResponse.json( { error: 'Failed to create sale' }, { status: 500 } ) } }