import { NextRequest, NextResponse } from 'next/server' import pool from '@/lib/db' import bcrypt from 'bcrypt' // POST /api/auth/login - Login with username and password export async function POST(request: NextRequest) { try { const body = await request.json() const { username, password } = body // Validate required fields if (!username || !password) { return NextResponse.json( { error: 'Username and password are required' }, { status: 400 } ) } // Find user by username const [rows] = await pool.execute( 'SELECT * FROM buyers WHERE username = ?', [username] ) const buyers = rows as any[] if (buyers.length === 0) { return NextResponse.json( { error: 'Invalid username or password' }, { status: 401 } ) } const buyer = buyers[0] // Verify password const isValidPassword = await bcrypt.compare(password, buyer.password) if (!isValidPassword) { return NextResponse.json( { error: 'Invalid username or password' }, { status: 401 } ) } // Create session cookie const response = NextResponse.json( { user: { id: buyer.id, username: buyer.username, email: buyer.email, }, }, { status: 200 } ) // 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 login:', error) return NextResponse.json( { error: 'Failed to login' }, { status: 500 } ) } }