import pool from '@/lib/database';
import type { RowDataPacket } from 'mysql2';

import bcrypt from 'bcrypt';

import { NextResponse, NextRequest } from 'next/server';

export async function POST(request: NextRequest) {
    const body = await request.json();
    const { email, password, id, rule } = body;

    try{
        if(!rule || rule === false){
            return NextResponse.json({
                status: "error",
                error: "Please read and accept the terms and conditions"
            }, { status: 400 });
        }
    }catch(e){
        console.log(e);
    }

    // bodyが空になっていないか
    if(!email || !password || !id || !rule){
        return NextResponse.json({
            status: "error",
            error: "Body Required"
        }, { status: 400 });
    }

    // パスワードが八文字以上か
    if(password.length < 8){
        return NextResponse.json({
            status: "error",
            error: "Password must be at least 8 characters long"
        }, { status: 400 });
    }

    // ユーザー名が英数字3文字以上か
    if(!/^[a-zA-Z0-9]{3,}$/.test(id)){
        return NextResponse.json({
            status: "error",
            error: "Username must be at least 3 alphanumeric characters"
        }, { status: 400 });
    }

    const [existingUsers] = await pool.execute<RowDataPacket[]>(
        "SELECT * FROM users WHERE id = ?",[id]
    );

    if(existingUsers.length === 0){
        const passwordHash = await bcrypt.hash(password, 10);

        const [result] = await pool.execute<RowDataPacket[]>(
            "INSERT INTO `users` (`id`, `password`, `email`, `mailverified`, `time`, `num`) VALUES (?, ?, ?, '0', current_timestamp(3), NULL)",
            [id, passwordHash, email]
        );

        if ((result as RowDataPacket).affectedRows === 1) {
            await fetch(request.nextUrl.protocol + request.nextUrl.host + "/api/mailverified/send", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    email: email,
                    user: id,
                })
            });

            return NextResponse.json({
                status: "success",
                message: "User created successfully"
            }, { status: 201 });
        } else {
            return NextResponse.json({
                status: "error",
                error: "Failed to create user"
            }, { status: 500 });
        }
    }else{
        return NextResponse.json({
            status: "error",
            error: "User already exists"
        }, { status: 400 });
    }
}
