import { db } from "../../lib/db";
import bcrypt from "bcrypt";
import { NextResponse } from "next/server";
import { v4 as uuidv4 } from "uuid";

export async function POST(req) {

    const { email, password, username } = await req.json();
    const userId = uuidv4();

    const [rows] = await (await db).query('SELECT * FROM users WHERE EMAIL = ? OR USERNAME = ? OR USER_ID = ?', [email, username, userId]);

    if (rows.length !== 0) {
        return NextResponse.json({ message: 'User already exists' }, { status: 409 });
    }


    const hash = await bcrypt.hash(password, 10);
    await (await db).query('INSERT INTO users (USER_ID, EMAIL, PASSWORD, USERNAME) VALUES (?, ?, ?, ?)', [userId, email, hash, username]);

    return NextResponse.json({ message: 'OK' });
}