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

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

module.exports = require("lodash");

/***/ }),

/***/ 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");

/***/ }),

/***/ 2066:
/***/ ((__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_serverError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2163);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6825);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5338);
/* harmony import */ var _package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_3__);
// @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_2___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  } = sanitizedReqBody;
    const userPreset = __webpack_require__(9258);
    const defaultFields = __webpack_require__(2439);
    const finalFields = [
        ...defaultFields.slice(0, 2),
        ...userPreset.fields,
        ...defaultFields.slice(2), 
    ];
    userPreset.fields = [
        ...finalFields
    ];
    /**
     * Send Response
     *
     * @description Send a boolean response
     */ try {
        /**
         * Create new user folder and file
         *
         * @description Create new user folder and file
         */ const userSchemaMainFilePath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${user.id}/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];
        /** @type {number | undefined} */ let existingTableIndex;
        let existingTable = targetDatabase.tables.filter((table, index)=>{
            if (table.tableName === "users") {
                existingTableIndex = index;
                return true;
            }
        });
        // if (typeof existingTableIndex !== "number")
        //     return res.json({ success: false });
        if (existingTable?.[0] && typeof existingTableIndex == "number") {
            targetDatabase.tables[existingTableIndex] = userPreset;
        } else {
            targetDatabase.tables.push(userPreset);
        }
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        /**
         * Check Children Databases
         *
         * @description Check Children Databases
         */ if (targetDatabase.childrenDatabases) {
            for(let i = 0; i < targetDatabase.childrenDatabases.length; i++){
                const childDb = targetDatabase.childrenDatabases[i];
                try {
                    const targetChild = userSchemaData.filter((db)=>db.dbFullName === childDb.dbFullName)[0];
                    targetChild.tables = targetDatabase.tables;
                    const targetDbRecord = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_0___default()(`SELECT * FROM user_databases WHERE user_id = ? AND db_full_name = ?`, [
                        user.id,
                        childDb.dbFullName
                    ]);
                    const newChildTableEntry = await _package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_3___default()({
                        dbFullName: "datasquirel",
                        tableName: "user_database_tables",
                        data: {
                            user_id: user.id,
                            db_id: targetDbRecord[0].id,
                            db_slug: targetDbRecord[0].db_slug,
                            table_name: "Users",
                            table_slug: "users"
                        }
                    });
                } catch (/** @type {any} */ error) {
                    _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
                        component: "/api/addUsersTableToDatabase/lines-100-115",
                        message: error.message,
                        user: user
                    });
                }
            }
        }
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        fs.writeFileSync(`${userSchemaMainFilePath}`, JSON.stringify(userSchemaData), "utf8");
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        const newTableEntry = await _package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_3___default()({
            dbFullName: "datasquirel",
            tableName: "user_database_tables",
            data: {
                user_id: user.id,
                db_id: dbId,
                db_slug: dbSlug,
                table_name: "Users",
                table_slug: "users"
            }
        });
        ////////////////////////////////////////
        const targetPath = path.join(process.cwd(), "/shell");
        const sanitizedDbName = dbFullName.replace(/[^a-z\_0-9]/g, "");
        const dbShellUpdate = execSync(`node createDbFromSchema.js --user ${user.id}  --database ${sanitizedDbName}`, {
            cwd: targetPath
        });
        console.log(dbShellUpdate.toString());
        ////////////////////////////////////////
        res.json({
            success: true
        });
    ////////////////////////////////////////
    } catch (/** @type {any} */ error1) {
        ////////////////////////////////////////
        _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
            component: "/api/addUsersTableToDatabase/main-catch-error",
            message: error1.message,
            user: user
        });
        res.json({
            success: false,
            msg: "Database Files could not be written!"
        });
    ////////////////////////////////////////
    }
}


/***/ }),

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

module.exports = JSON.parse('[{"fieldName":"id","dataType":"BIGINT","notNullValue":true,"primaryKey":true,"autoIncrement":true},{"fieldName":"uuid","dataType":"UUID","defaultValueLiteral":"UUID()"},{"fieldName":"date_created","dataType":"VARCHAR(250)","nullValue":true},{"fieldName":"date_created_code","dataType":"BIGINT","nullValue":true},{"fieldName":"date_created_timestamp","dataType":"TIMESTAMP","defaultValueLiteral":"CURRENT_TIMESTAMP"},{"fieldName":"date_updated","dataType":"VARCHAR(250)","nullValue":true},{"fieldName":"date_updated_code","dataType":"BIGINT","nullValue":true},{"fieldName":"date_updated_timestamp","dataType":"TIMESTAMP","defaultValueLiteral":"CURRENT_TIMESTAMP","onUpdateLiteral":"CURRENT_TIMESTAMP"}]');

/***/ })

};
;

// 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,5338,9258], () => (__webpack_exec__(2066)));
module.exports = __webpack_exports__;

})();