import { NSQLITE_TURBOCI_ADMIN_USERS, NSQLiteTables } from "@/src/db/types";
import { _n } from "@/src/exports/client-exports";
import grabDeploymentUserDirNames from "@/src/utils/grab-deployment-user-dir-names";
import NSQLite from "@moduletrace/nsqlite";
import { execSync } from "child_process";

type Params = {
    user_id: string | number;
};

export default async function deleteDeploymentUser({ user_id }: Params) {
    const target_user_res = await NSQLite.select<
        NSQLITE_TURBOCI_ADMIN_USERS,
        (typeof NSQLiteTables)[number]
    >({
        table: "users",
        targetId: _n(user_id),
    });

    const target_user = target_user_res.singleRes;

    if (
        !target_user?.id ||
        !target_user.username ||
        target_user.is_super_admin
    ) {
        return;
    }

    const { username } = target_user;

    console.log("username", username);

    const { force_command_file, sshd_config_file } = grabDeploymentUserDirNames(
        { user: target_user },
    );

    let cmd = `/bin/bash << 'TURBOCIHEREDOC'\n`;

    // cmd += `userdel -r ${username}\n`;
    // cmd += `pkill -u ${username} || echo "User Deleted!"\n`;
    cmd += `deluser --remove-all-files ${username} || echo "User Deleted!"\n`;

    cmd += `rm -f ${force_command_file}\n`;
    cmd += `rm -f ${sshd_config_file}\n`;

    cmd += `TURBOCIHEREDOC\n`;

    execSync(cmd);

    NSQLite.delete({ table: "users", targetId: target_user.id });

    return;
}
