import { WebSocketMessageParam } from "@/src/types";
import sendData from "../(utils)/send-data";
import sendError from "../(utils)/send-error";
import grabConnectedWebsocketUserdata from "../(utils)/grab-connected-websocket-user-data";
import killPort from "../(utils)/kill-port";

export default async function socketClientKillPort({
    ws,
    data,
}: WebSocketMessageParam) {
    try {
        const user = ws.data.user;
        const service = data?.service;
        const server = data?.server;
        const port = data?.port;

        const connected_user_data = grabConnectedWebsocketUserdata({ user });

        if (port) {
            await killPort({ port, exec_options: { stdio: "inherit" } });

            connected_user_data.ports = connected_user_data.ports.filter(
                (p) => p != port,
            );
        }

        sendData(ws, {
            event: "server:killed-port",
        });
    } catch (error: any) {
        sendError(ws, "Service Server Logs Error! " + error.message);
    }
}
