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

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

    if (!id) {
        return NextResponse.json({ error: 'Missing id' }, { status: 400 });
    }

    const [rows] = await (await db).query("SELECT * FROM trains WHERE GARE_ID = ?", [id]);
    const [rows2] = await (await db).query("SELECT ID FROM gares WHERE ID = ?", [id]);

    if (rows.length === 0 && rows2.length === 0) {
        return NextResponse.json({ error: 'Not found' }, { status: 404 });
    } else if (rows.length === 0 && rows2.length !== 0) {
        return NextResponse.json({ error: 'No trains found for this station' }, { status: 410 });
    }

    return NextResponse.json(rows);
}

export async function POST(req) {
    notifyClients('db-update', req.body);
    return NextResponse.json({ message: 'OK'}, { status: 200 })
}