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

export async function GET(req) {
    const sessionId = (await cookies()).get('session')?.value;

    if (!sessionId) {
        return NextResponse.json({ isLoggedIn: false }, { status: 401 });
    }

    const [rows] = await (await db).query('SELECT USER_ID FROM sessions WHERE SESSION_ID = ?', [sessionId]);

    if (rows.length === 0) {
        return NextResponse.json({ isLoggedIn: false }, { status: 401 });
    }

    const userId = rows[0].USER_ID;
    const [user] = await (await db).query('SELECT USERNAME, EMAIL, EMAIL_VALID, RIGHTS FROM users WHERE USER_ID = ?', [userId]);

    return NextResponse.json({ isLoggedIn: true, user: user.length ? user[0] : null }, { status: 200 });
}