import { NextResponse } from 'next/server'; import pool from '@/lib/db'; import bcrypt from 'bcryptjs'; export async function POST(request: Request) { let connection; try { const { username, nim, password } = await request.json(); // Validate input if (!username || !nim || !password) { return NextResponse.json( { error: 'Semua field harus diisi' }, { status: 400 } ); } // Validate NIM format (11 characters) if (nim.length !== 11) { return NextResponse.json( { error: 'NIM harus 11 karakter' }, { status: 400 } ); } // Get connection from pool connection = await pool.getConnection(); // Check if NIM exists in mahasiswa table const [mahasiswa]: any = await connection.execute( 'SELECT * FROM mahasiswa WHERE nim = ?', [nim] ); if (mahasiswa.length === 0) { connection.release(); return NextResponse.json( { error: 'NIM tidak terdaftar sebagai mahasiswa' }, { status: 400 } ); } // Check if NIM already exists in user table const [existingUsers]: any = await connection.execute( 'SELECT * FROM user WHERE nim = ?', [nim] ); if (existingUsers.length > 0) { connection.release(); return NextResponse.json( { error: 'NIM sudah terdaftar sebagai pengguna' }, { status: 400 } ); } // Hash password const hashedPassword = await bcrypt.hash(password, 10); // Insert new user await connection.execute( 'INSERT INTO user (nim, username, password, role, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())', [nim, username, hashedPassword, 'mahasiswa'] ); connection.release(); return NextResponse.json( { message: 'Registrasi berhasil' }, { status: 201 } ); } catch (error) { if (connection) { connection.release(); } console.error('Registration error:', error); return NextResponse.json( { error: 'Terjadi kesalahan saat registrasi' }, { status: 500 } ); } }