import { Server } from "socket.io";
import { NextResponse } from "next/server";

let io;

export async function POST(req) {
    if (!res.socket.server) {
        console.log('Init socket server');
        io = new Server(req.socket.server, {
            cors: {
                origin: '*',
                methods: ['GET', 'POST'],
            },
        });

        io.on('connection', (socket) => {
            console.log('Client connected');

            socket.on('disconnect', () => {
                console.log('Client disconnected');
            });
        });

        res.socket.server = io;
    }

    return NextResponse.json({ message: 'Socket server initialized' }, { status: 200 });
}

export async function GET(req) {
    if (!res.socket.server) {
        console.log('Init socket server');
        io = new Server(req.socket.server, {
            cors: {
                origin: '*',
                methods: ['GET', 'POST'],
            },
        });

        io.on('connection', (socket) => {
            console.log('Client connected');

            socket.on('disconnect', () => {
                console.log('Client disconnected');
            });
        });

        res.socket.server = io;
    }

    return NextResponse.json({ message: 'Socket server initialized' }, { status: 200 });
}