"use strict";
(() => {
var exports = {};
exports.id = 4739;
exports.ids = [4739];
exports.modules = {

/***/ 2261:
/***/ ((module) => {

module.exports = require("serverless-mysql");

/***/ }),

/***/ 4300:
/***/ ((module) => {

module.exports = require("buffer");

/***/ }),

/***/ 6113:
/***/ ((module) => {

module.exports = require("crypto");

/***/ }),

/***/ 7147:
/***/ ((module) => {

module.exports = require("fs");

/***/ }),

/***/ 3685:
/***/ ((module) => {

module.exports = require("http");

/***/ }),

/***/ 1017:
/***/ ((module) => {

module.exports = require("path");

/***/ }),

/***/ 4512:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ 
const fs = __webpack_require__(7147);
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * ==============================================================================
 * Main Function
 * ==============================================================================
 * @param {{
 *  rootFolderPath: string,
 * }} params - params
 *
 * @returns {boolean} operation successful or not
 */ module.exports = function deleteFolderRecursively({ rootFolderPath  }) {
    try {
        /**
         * Recursive Copy Function
         *
         * @description Recursive Copy Function
         * @param {string} srcPath
         */ function deleteFiles(srcPath) {
            try {
                const files = fs.readdirSync(srcPath);
                for(let i = 0; i < files.length; i++){
                    const file = files[i];
                    if (file?.match(/\..{2,5}$/)) {
                        fs.unlinkSync(`${srcPath}/${file}`);
                    } else {
                        deleteFiles(`${srcPath}/${file}`);
                    }
                }
                fs.rmdirSync(`${srcPath}`);
            } catch (error) {
                try {
                    fs.unlinkSync(srcPath);
                } catch (err) {}
            }
        }
        deleteFiles(rootFolderPath);
        fs.rmSync(`${rootFolderPath}`, {
            recursive: true,
            force: true
        });
        return true;
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    } catch (/** @type {any} */ error) {
        console.log("ERROR in deleteFolderRecursively.js function =>", error.message);
        return false;
    }
}; ////////////////////////////////////////////////
 ////////////////////////////////////////////////
 ////////////////////////////////////////////////


/***/ }),

/***/ 3456:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ handler)
/* harmony export */ });
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2224);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _functions_backend_deleteFolderRecursively__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4512);
/* harmony import */ var _functions_backend_deleteFolderRecursively__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_deleteFolderRecursively__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2163);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6825);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_3__);
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ const fs = __webpack_require__(7147);
const path = __webpack_require__(1017);




//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
 * API handler
 * ==============================================================================
 * @type {import("next").NextApiHandler}
 */ async function handler(req, res) {
    /**
     * Check method
     *
     * @description Check request method and return if invalid
     */ if (req.method !== "POST") return res.json({
        msg: "Failed!"
    });
    /**
     * User auth
     *
     * @description Authenticate user
     */ const user = await _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_3___default()(req, res, true);
    if (!user) {
        return res.json({
            success: false,
            msg: "Unauthorized"
        });
    }
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    const isProduction = "production".match(/prod/i);
    /**
     * Send Response
     *
     * @description Send a boolean response
     */ try {
        /**
         * Create new user folder and file
         *
         * @description Create new user folder and file
         */ const deleteUser = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM users WHERE id='${user.id}'`);
        const deleteUserUser = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM user_users WHERE invited_user_id='${user.id}' OR user_id='${user.id}'`);
        const deleteDelegatedUserTables = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM delegated_user_tables WHERE delegated_user_id='${user.id}' OR root_user_id='${user.id}'`);
        const deleteUserDatabases = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM user_databases WHERE user_id='${user.id}'`);
        const deleteUserDatabaseTables = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM user_database_tables WHERE user_id='${user.id}'`);
        const deleteUserMedia = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM user_media WHERE user_id='${user.id}'`);
        const deleteDelegatedUsers = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM delegated_users WHERE user_id='${user.id}' OR delegated_user_id='${user.id}'`);
        const deleteUnsubscribes = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM unsubscribes WHERE user_id='${user.id}'`);
        const deleteNotifications = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM notifications WHERE user_id='${user.id}'`);
        const deleteApiKeys = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM api_keys WHERE user_id='${user.id}'`);
        const deleteInvitations = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DELETE FROM invitations WHERE inviting_user_id='${user.id}' OR invited_user_email='${user.email}'`);
        const mariadbUsersArray = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`SELECT * FROM mariadb_users WHERE user_id = ?`, [
            user.id
        ]);
        for(let i = 0; i < mariadbUsersArray.length; i++){
            const mariadbUser = mariadbUsersArray[i];
            const { username , host  } = mariadbUser;
            const deleteMariadbUsers = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DROP USER IF EXISTS '${username}'@'${host}'`);
        }
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        const userDatabases = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`SHOW databases LIKE 'datasquirel_user_${user.id}_%'`);
        for(let i1 = 0; i1 < userDatabases.length; i1++){
            const dbObj = userDatabases[i1];
            const dbName = Object.values(dbObj);
            await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`DROP database IF EXISTS ${dbName}`);
        }
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        const userSchemaPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${user.id}/main.json`;
        if (fs.existsSync(userSchemaPath)) fs.unlinkSync(userSchemaPath);
        const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
        if (!STATIC_ROOT) {
            console.log("Static File ENV not Found!");
            throw new Error("No Static Path!");
        }
        const userMediaFolder = path.join(STATIC_ROOT, `images/user-images/user-${user.id}`);
        if (fs.existsSync(userMediaFolder)) _functions_backend_deleteFolderRecursively__WEBPACK_IMPORTED_MODULE_1___default()({
            rootFolderPath: userMediaFolder
        });
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        res.json({
            success: true
        });
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    } catch (/** @type {any} */ error) {
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
        _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_2___default()({
            component: "/api/addApiKey/catch-error",
            message: error.message,
            user: user
        });
        res.json({
            success: false,
            msg: "User could not be deleted!"
        });
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    ////////////////////////////////////////////////
    }
}


/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [2224,2163,6825], () => (__webpack_exec__(3456)));
module.exports = __webpack_exports__;

})();