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

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

export async function POST(request: NextRequest) {
    const body = await request.json();
    const { code } = body;

    const [rows] = await pool.query<RowDataPacket[]>(
        'SELECT * FROM mailverifiedcode WHERE code = ?',
        [code]
    );

    if (rows.length === 0) {
        return NextResponse.json({status: "error", message: 'Code not found' }, { status: 401 });
    }else{
        if(rows[0].code === code){
            await pool.query<RowDataPacket[]>(
                'UPDATE `users` SET `mailverified` = 1 WHERE `users`.`id` = ?',
                [rows[0].user]
            );

            return NextResponse.json({status: "success", message: 'Code verified' }, { status: 200 });
        }
    }
}