import { NextResponse } from "next/server";
import { db } from "@/app/lib/db";

export async function GET(req) {
    const length = req.nextUrl.searchParams.get('length');
    const search = req.nextUrl.searchParams.get('search');

    if (length) {
        const [rows] = await (await db).query('SELECT COUNT(USER_ID) FROM users');

        return NextResponse.json(rows[0]['COUNT(USER_ID)']);
    } else if (search) {
        const [rows] = await (await db).query('SELECT USER_ID, EMAIL, EMAIL_VALID, USERNAME, CREATION_TIME, LAST_LOGIN, ENABLED FROM users WHERE USERNAME LIKE ? OR EMAIL LIKE ? LIMIT 25', [`%${search}%`, `%${search}%`]);

        return NextResponse.json(rows);
    } else {
        const [rows] = await (await db).query('SELECT USER_ID, EMAIL, EMAIL_VALID, USERNAME, CREATION_TIME, LAST_LOGIN, ENABLED FROM users LIMIT 25');

        return NextResponse.json(rows);
    }
}

export async function PUT(req) {
    const { id, username, email, email_valid } = await req.json();

    await (await db).query('UPDATE users SET USERNAME = ?, EMAIL = ?, EMAIL_VALID = ? WHERE USER_ID = ?', [username, email, email_valid, id]);

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