import { type ServerWebSocket, type Subprocess } from "bun";
import socketInit from "@WS/functions/socket-init";
import type { DATASQUIREL_LoggedInUser } from "@moduletrace/datasquirel/dist/package-shared/types";
import socketOpen from "@WS/functions/socket-open";
import socketClose from "@WS/functions/socket-close";
import socketMessage from "@WS/functions/socket-message";
import setupDSQLDb from "@/utils/setup-db";
import debugLog from "@/package-shared/utils/logging/debug-log";

setupDSQLDb();

export type WebSocketData = {
    user: DATASQUIREL_LoggedInUser;
};

declare global {
    var ACTIVE_USERS: (DATASQUIREL_LoggedInUser & {
        ws: ServerWebSocket<WebSocketData>;
    })[];
}

global.ACTIVE_USERS = [];

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) {
            socketMessage({ ws, message });
        },
        async open(ws) {
            socketOpen({ ws });
        },
        async close(ws, code, message) {
            socketClose({ ws });
        },
        idleTimeout: 600,
    },
    port: process.env.DSQL_WEBSOCKET_PORT,
});

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