import { AppData } from "@/src/data/app-data";
import {
    NSQLITE_TURBOCI_ADMIN_USERS_PORTS,
    NSQLiteTables,
} from "@/src/db/types";
import { User } from "@/src/types";
import BunSQLite from "@moduletrace/bun-sqlite";
import { execSync, ExecSyncOptions } from "child_process";
import killPort from "./kill-port";

type Params = {
    user: User;
};

export default async function killAllTtydPorts({ user }: Params) {
    const user_ports_res = await BunSQLite.select<
        NSQLITE_TURBOCI_ADMIN_USERS_PORTS,
        (typeof NSQLiteTables)[number]
    >({
        table: "users_ports",
        query: { query: { user_id: { value: String(user.id) } } },
    });

    if (user_ports_res?.payload?.[0]) {
        for (let i = 0; i < user_ports_res.payload.length; i++) {
            const user_port = user_ports_res.payload[i];
            if (!user_port.port) {
                continue;
            }

            await killPort({ port: user_port.port });

            await BunSQLite.delete<
                NSQLITE_TURBOCI_ADMIN_USERS_PORTS,
                (typeof NSQLiteTables)[number]
            >({
                table: "users_ports",
                query: { query: { port: { value: String(user_port.port) } } },
            });
        }
    }
}

// const start_port = AppData["DynamicPortStart"];
// const end_port = start_port + 100;
// const kill_ports_cmd = `ss -tlnp | awk 'NR>1 {split($4, a, ":"); port=a[length(a)]; if (port >= ${start_port} && port <= ${end_port}) print $6}' | grep -oP 'pid=\\K[0-9]+' | xargs -r kill -9`;

// execSync(kill_ports_cmd, {
//     ...exec_options,
// });

// sudo ss -tlnp | awk 'NR>1 {split($4, a, ":"); port=a[length(a)]; if (port >= 4700 && port <= 4800) print $6}' | grep -oP 'pid=\K[0-9]+' | xargs -r sudo kill -9

// ss -tlnp | awk 'NR>1 {split($4, a, ":"); port=a[length(a)]; if (port >= 4700 && port <= 4800) print $6}' | grep -oP 'pid=\K[0-9]+' | xargs -r sudo kill -9
