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

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

module.exports = require("sanitize-html");

/***/ }),

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

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

/***/ }),

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

module.exports = require("buffer");

/***/ }),

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

module.exports = require("child_process");

/***/ }),

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

module.exports = require("crypto");

/***/ }),

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

module.exports = require("fs");

/***/ }),

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

module.exports = require("http");

/***/ }),

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

module.exports = require("path");

/***/ }),

/***/ 9052:
/***/ ((__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_checkUserRights__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8999);
/* harmony import */ var _functions_backend_checkUserRights__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_checkUserRights__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _functions_backend_grabDelegatedUserFromCookie__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1352);
/* harmony import */ var _functions_backend_grabDelegatedUserFromCookie__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_grabDelegatedUserFromCookie__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2163);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6825);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _package_shared_functions_backend_db_updateDbEntry__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5886);
/* harmony import */ var _package_shared_functions_backend_db_updateDbEntry__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_db_updateDbEntry__WEBPACK_IMPORTED_MODULE_5__);
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ const fs = __webpack_require__(7147);
const path = __webpack_require__(1017);
const { execSync  } = __webpack_require__(2081);






/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * 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_4___default()(req, res, true);
    if (!user) {
        return res.json({
            success: false,
            msg: "Unauthorized"
        });
    }
    /**
     * User auth
     *
     * @description Authenticate user
     */ const sanitizedReqBody = req.body;
    const { dbFullName , dbSlug , dbId , tableNameOld , payload , delegated  } = sanitizedReqBody;
    const { tableName , tableFullName , tableDescription  } = payload;
    /**
     * User auth
     *
     * @description Authenticate user
     */ if (!tableName?.match(/./) || tableName.match(/[^a-zA-Z0-9-_]/)) {
        return res.json({
            success: false,
            msg: "Bad Input"
        });
    }
    /**
     * Send Response
     *
     * @description Send a boolean response
     */ try {
        /**
         * Check if user has rights to this table
         *
         * @description Check if user has rights to this table
         */ const delegatedUser = await _functions_backend_grabDelegatedUserFromCookie__WEBPACK_IMPORTED_MODULE_2___default()({
            databaseSlug: dbSlug,
            request: req,
            user: user,
            query: req.query
        });
        const checkUserRightsBoolean = await _functions_backend_checkUserRights__WEBPACK_IMPORTED_MODULE_1___default()({
            user: user,
            confirmedDelegetedUser: delegatedUser,
            database: dbSlug,
            table: tableNameOld,
            dbId: dbId,
            priviledgeRegex: /Edit Table/i
        });
        if (!checkUserRightsBoolean) {
            console.log("User Unauthorized");
            return res.json({
                success: false,
                msg: "Unauthorized"
            });
        }
        const userId = delegatedUser?.rootUserId ? delegatedUser.rootUserId : user.id;
        /**
         * Create new user folder and file
         *
         * @description Create new user folder and file
         */ const userSchemaMainFilePath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`;
        /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} */ let userSchemaData = JSON.parse(fs.readFileSync(userSchemaMainFilePath, "utf8"));
        let targetDatabase = userSchemaData.filter((db)=>db.dbFullName === dbFullName)[0];
        let existingTableIndex;
        let existingTable = targetDatabase.tables.filter((table, index)=>{
            if (table.tableName === tableNameOld) {
                existingTableIndex = index;
                return true;
            }
        });
        if (existingTable && existingTable[0]) {
            existingTable[0].tableName = tableName;
            existingTable[0].tableNameOld = tableNameOld;
            existingTable[0].tableFullName = tableFullName;
            tableDescription && (existingTable[0].tableDescription = tableDescription);
            if (existingTable[0].childrenTables) {
                existingTable[0].childrenTables.forEach((childTable)=>{
                    try {
                        const childDb = userSchemaData.filter((db)=>db.dbFullName === childTable.dbNameFull)[0];
                        const childTableObject = childDb.tables.filter((table)=>{
                            if (table.tableName === childTable.tableName) {
                                return true;
                            }
                        })[0];
                        childTableObject.childTableName = tableName;
                    } catch (/** @type {any} */ error) {
                        _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_3___default()({
                            component: "/api/updateUserTable/lines-131-138",
                            message: error.message,
                            user: user
                        });
                    }
                });
            }
        } else {
            throw new Error("Table Does not exist");
        }
        fs.writeFileSync(`${userSchemaMainFilePath}`, JSON.stringify(userSchemaData), "utf8");
        ////////////////////////////////////////
        const updateTable = await _package_shared_functions_backend_db_updateDbEntry__WEBPACK_IMPORTED_MODULE_5___default()({
            dbFullName: "datasquirel",
            tableName: "user_database_tables",
            identifierColumnName: "table_slug",
            identifierValue: tableNameOld,
            data: {
                table_name: tableFullName,
                table_slug: tableName,
                table_description: tableDescription
            }
        });
        if (delegated && delegatedUser) {
            const updateDelegatedTable = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`UPDATE delegated_user_tables SET \`table\`=? WHERE delegated_user_id=? AND root_user_id=? AND \`table\`=? AND \`database\`=?`, [
                tableName,
                user.id,
                delegatedUser.rootUserId,
                tableNameOld,
                dbSlug, 
            ]);
        }
        ////////////////////////////////////////
        const targetPath = path.join(process.cwd(), "/shell");
        const sanitizedDbName = dbFullName.replace(/[^a-z\_0-9]/g, "");
        const dbShellUpdate = execSync(`node createDbFromSchema.js --user ${userId} --database ${sanitizedDbName}`, {
            cwd: targetPath
        });
        console.log(dbShellUpdate.toString());
        ////////////////////////////////////////
        res.json({
            success: true
        });
    ////////////////////////////////////////
    } catch (/** @type {any} */ error) {
        ////////////////////////////////////////
        _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_3___default()({
            component: "/api/updateUserTable/main-catch-error",
            message: error.message,
            user: user
        });
        res.json({
            success: false,
            msg: "Database Files could not be written!"
        });
    ////////////////////////////////////////
    }
}


/***/ })

};
;

// 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,3017,3403,7547,5886,1352,8999], () => (__webpack_exec__(9052)));
module.exports = __webpack_exports__;

})();