// @ts-check

import { execSync } from "child_process";

/**
 *
 * @param {number | string | null | undefined} port
 * @returns
 */
export default async function killProcessOnPort(
    port: number | string | null | undefined
) {
    if (!port) {
        console.error("Error: No port specified");
        return;
    }

    const targetPort = parseInt(port.toString());

    if (isNaN(targetPort)) {
        console.error("Error: Port must be a number");
        return;
    }

    if (typeof targetPort !== "number") {
        console.error("Error: Port must be a number");
        return;
    }

    const processId = (() => {
        try {
            if (process.platform.match(/win/i)) {
                const readNetStat = execSync(
                    `netstat -ano | findstr :${targetPort}`
                ).toString("utf-8");
                const firstLine = readNetStat.match(/.*/)?.[0].trim();
                const PID = firstLine?.split(" ").at(-1);
                return PID;
            }

            return execSync(
                `lsof -i :${targetPort} | awk '$1 == "COMMAND" { next } { print $2 }'`
            )
                .toString()
                .trim();
        } catch (/** @type {any} */ error: any) {
            console.log(
                `Error finding PID on ${process.platform}:`,
                error.message
            );
            return null;
        }
    })();

    if (!processId) {
        console.error(`Error: No process found on port ${targetPort}`);
        return;
    }

    try {
        if (process.platform.match(/win/i)) {
            execSync(`taskkill /F /PID ${processId} /T`);
        } else {
            execSync(`kill -9 ${processId}`);
        }
        console.log(`Killed process ${processId} on port ${targetPort}`);
    } catch (/** @type {any} */ error: any) {
        console.error("Error:", error.message);
    }
}