import { NextRequest, NextResponse } from 'next/server' import pool from '@/lib/db' import bcrypt from 'bcrypt' // POST /api/auth/register - Register a new buyer export async function POST(request: NextRequest) { try { const body = await request.json() const { username, password, email, referral_id } = body // Validate required fields if (!username || !password || !email) { return NextResponse.json( { error: 'Username, password, and email are required' }, { status: 400 } ) } // Validate username length if (username.length < 3) { return NextResponse.json( { error: 'Username must be at least 3 characters' }, { status: 400 } ) } // Validate password length if (password.length < 6) { return NextResponse.json( { error: 'Password must be at least 6 characters' }, { status: 400 } ) } // Validate email format const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ if (!emailRegex.test(email)) { return NextResponse.json( { error: 'Invalid email format' }, { status: 400 } ) } // Check if username already exists const [existingUsername] = await pool.execute( 'SELECT id FROM buyers WHERE username = ?', [username] ) if ((existingUsername as any[]).length > 0) { return NextResponse.json( { error: 'Username already exists' }, { status: 400 } ) } // Check if email already exists const [existingEmail] = await pool.execute( 'SELECT id FROM buyers WHERE email = ?', [email] ) if ((existingEmail as any[]).length > 0) { return NextResponse.json( { error: 'Email already exists' }, { status: 400 } ) } // Hash password const hashedPassword = await bcrypt.hash(password, 10) // Insert new buyer const [result] = await pool.execute( 'INSERT INTO buyers (username, password, email) VALUES (?, ?, ?)', [username, hashedPassword, email] ) const insertId = (result as any).insertId // Fetch the created buyer (without password) const [rows] = await pool.execute( 'SELECT id, username, email FROM buyers WHERE id = ?', [insertId] ) const buyer = (rows as any[])[0] // Handle referral if provided if (referral_id) { const referrerId = parseInt(referral_id, 10) // Validate that referrer exists and is not the same as the new user if (referrerId && referrerId !== buyer.id) { const [referrerRows] = await pool.execute( 'SELECT id FROM buyers WHERE id = ?', [referrerId] ) if ((referrerRows as any[]).length > 0) { // Create referral record await pool.execute( 'INSERT INTO referrals (referrer, referree) VALUES (?, ?)', [referrerId, buyer.id] ) } } } // Create session cookie const response = NextResponse.json( { user: { id: buyer.id, username: buyer.username, email: buyer.email, }, }, { status: 201 } ) // Set secure cookie with buyer_id response.cookies.set('buyer_id', buyer.id.toString(), { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', maxAge: 60 * 60 * 24 * 7, // 7 days path: '/', }) return response } catch (error) { console.error('Error during registration:', error) return NextResponse.json( { error: 'Failed to register' }, { status: 500 } ) } }