import { AppData } from "../data/app-data";
import { WebSocketConnectedUserData, WebSocketData } from "../types";
import socketClose from "./socket-close";
import socketInit from "./socket-init";
import socketMessage from "./socket-message";
import socketOpen from "./socket-open";

declare global {
    var WEBSOCKET_CONNECTED_USERS_DATA: WebSocketConnectedUserData[];
}

global.WEBSOCKET_CONNECTED_USERS_DATA = [];

const server = Bun.serve<WebSocketData>({
    async fetch(req, server) {
        const { user } = await socketInit({ req });

        if (!user?.logged_in_status) {
            return new Response("Unauthorized!");
        }

        const success = server.upgrade(req, {
            data: { user },
        });

        if (success) {
            return undefined;
        }

        return new Response("Web Socket Connection Failed!");
    },
    websocket: {
        async message(ws, message) {
            if (typeof message == "string") {
                await socketMessage({ ws, message });
            }
        },
        async open(ws) {
            await socketOpen({ ws });
        },
        async close(ws, code, message) {
            await socketClose({ ws });
        },
        idleTimeout: 600,
        maxPayloadLength: 1024 * 1024 * 10,
    },
    port: AppData["WebsocketPort"],
});

console.log(`Websocket Listening on http://${server.hostname}:${server.port}`);
