import { NextRequest, NextResponse } from 'next/server' import { cookies } from 'next/headers' import pool from '@/lib/db' // POST /api/notifications/subscribe - Subscribe to notifications export async function POST(request: NextRequest) { try { // Get buyer_id from session cookie if logged in const cookieStore = await cookies() const buyerIdCookie = cookieStore.get('buyer_id')?.value const buyer_id = buyerIdCookie ? parseInt(buyerIdCookie, 10) : null const body = await request.json() const { email, phone } = body // Validate that at least one field is provided if (!email && !phone) { return NextResponse.json( { error: 'Email or phone number is required' }, { status: 400 } ) } // Validate email format if provided if (email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ if (!emailRegex.test(email)) { return NextResponse.json( { error: 'Invalid email format' }, { status: 400 } ) } } // Validate phone format if provided (basic validation) if (phone) { const phoneRegex = /^[+]?[\d\s\-()]{10,15}$/ if (!phoneRegex.test(phone)) { return NextResponse.json( { error: 'Invalid phone number format' }, { status: 400 } ) } } // Insert email subscription if provided // Using INSERT IGNORE to handle duplicate addresses (address is now primary key) if (email) { await pool.execute( 'INSERT IGNORE INTO notification_subscribers (buyer_id, type, address) VALUES (?, ?, ?)', [buyer_id, 'email', email.trim()] ) } // Insert phone subscription if provided // Using INSERT IGNORE to handle duplicate addresses (address is now primary key) if (phone) { await pool.execute( 'INSERT IGNORE INTO notification_subscribers (buyer_id, type, address) VALUES (?, ?, ?)', [buyer_id, 'phone', phone.trim()] ) } return NextResponse.json( { success: true, message: 'Successfully subscribed to notifications' }, { status: 200 } ) } catch (error) { console.error('Error subscribing to notifications:', error) return NextResponse.json( { error: 'Failed to subscribe to notifications' }, { status: 500 } ) } }