import {
    TooManyConnectionError,
    tooManyConnectionError,
} from "@src/lib/errors.ts";
import { err, ok, Result } from "@shared/utils/result.ts";

const MAX_CONNECTIONS_PER_TOKEN = 2;
const MAX_CONNECTIONS = 500;

class WebSocketManager {
    private adminSockets: Map<string, WebSocket[]> = new Map();
    private userSockets: Map<string, WebSocket[]> = new Map();
    private connectionsCounter: number = 0;

    public addAdminClient(
        token: string,
        socket: WebSocket,
    ): Result<void, TooManyConnectionError> {
        if (this.connectionsCounter > MAX_CONNECTIONS) {
            return err(tooManyConnectionError("Too many connections"));
        }

        const sockets = this.adminSockets.get(token);

        if (!sockets) {
            const sockets = [socket];
            this.adminSockets.set(token, sockets);
            this.connectionsCounter++;
            return ok();
        } else if (sockets.length < MAX_CONNECTIONS_PER_TOKEN) {
            sockets.push(socket);
            this.connectionsCounter++;
            return ok();
        } else {
            return err(tooManyConnectionError("Too many connections"));
        }
    }
}
