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

export async function POST(req) {
    const { email, password } = await req.json();

    const [rows] = await (await db).query('SELECT EMAIL, PASSWORD, USER_ID, ENABLED FROM users WHERE email = ?', [email]);

    if (rows.length === 0) {
        return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
    }

    const user = rows[0];

    if (!await bcrypt.compare(password, user.PASSWORD)) {
        return NextResponse.json({ message: 'Bad credentials' }, { status: 406 });
    }

    if (!user.ENABLED) {
        return NextResponse.json({ message: 'Account disabled' }, { status: 403 });
    }

    const sessionId = uuidv4();
    await (await db).query('INSERT INTO sessions (SESSION_ID, USER_ID) VALUES (?, ?)', [sessionId, user.USER_ID]);

    await (await db).query('UPDATE users SET LAST_LOGIN = NOW() WHERE USER_ID = ?', [user.USER_ID]);

    const response = NextResponse.json({ message: 'OK' });
    response.headers.set('Set-Cookie', serialize('session', sessionId, {
        httpOnly: true,
        secure: false, //process.env.NODE_ENV === 'production',
        maxAge: 60 * 60 * 24 * 7,
        path: '/',
    }));

    return response;
}