// Import the framework and instantiate it
import Fastify from 'fastify'
import {fastifyWebsocket} from '@fastify/websocket';

const server = Fastify({
	logger: true
});

server.register(fastifyWebsocket);

server.get("/api/ws/room", { websocket: true }, function wsHandler (socket) {
    console.log("Client connected!");

	console.log(socket);

	socket.on('upgrade', () => {
        console.log('upgraded');
    });

    socket.on('message', message => {
        console.log('Message from server:', message);
        socket.send(`Echo: ${message}`);
    });

    socket.on('close', () => {
        console.log('WebSocket connection closed');
    });

    socket.on('error', error => {
        console.error('WebSocket error:', error);
    });
});

// Run the server!
try {
	// Note: host needs to be 0.0.0.0 rather than omitted or localhost, otherwise
	// it always returns an empty reply when used inside docker...
	// See: https://github.com/fastify/fastify/issues/935
	await server.listen({ port: parseInt(process.env["PORT"] ?? "3000"), host: "0.0.0.0" })
} catch (err) {
	server.log.error(err)
	process.exit(1)
}