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

export async function GET(req) {
    const [rows] = await (await db).query("SELECT ID, USER_ID FROM gares WHERE SHARED = 1");

    if (rows.length === 0) {
        return NextResponse.json({ train: {}, user: {} }, { status: 404 });
    }

    // Select a random row
    const randomRow = rows[Math.floor(Math.random() * rows.length)];
    const [rows1] = await (await db).query("SELECT DESTINATION, NUMBER FROM trains WHERE GARE_ID = ?", [randomRow.ID]);

    // Select a random row
    const randomRow1 = rows1[Math.floor(Math.random() * rows1.length)];

    const [rows2] = await (await db).query("SELECT USERNAME FROM users WHERE USER_ID = ?", [randomRow.USER_ID]);

    return NextResponse.json({ train: randomRow1, user: rows2 });
}