"use strict";
(() => {
var exports = {};
exports.id = 590;
exports.ids = [590];
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");

/***/ }),

/***/ 6772:
/***/ ((__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_functions_backend_varDatabaseDbHandler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1311);
/* harmony import */ var _package_shared_functions_backend_varDatabaseDbHandler__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_varDatabaseDbHandler__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_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2224);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3__);
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ const fs = __webpack_require__(7147);




/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * 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 { id , user_id , table_name , table_slug , table_description  } = sanitizedReqBody.table;
    const { db_full_name  } = sanitizedReqBody.database;
    await _package_shared_functions_backend_varDatabaseDbHandler__WEBPACK_IMPORTED_MODULE_0___default()({
        database: db_full_name,
        queryString: `DROP TABLE \`${table_slug}\``
    });
    const deleteTableQuery = id ? `DELETE FROM user_database_tables WHERE id=?` : `DELETE FROM user_database_tables WHERE table_slug=? AND user_id=? AND db_id=?`;
    const deleteTableQueryValues = id ? [
        id
    ] : [
        table_slug,
        user.id,
        sanitizedReqBody.database.id
    ];
    await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(deleteTableQuery, deleteTableQueryValues);
    try {
        /**
         * Send Response
         *
         * @description Send a boolean response
         */ 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 targetDatabaseIndex;
        let targetDatabase = userSchemaData.filter((databaseObject, index)=>{
            if (databaseObject.dbFullName === db_full_name) {
                targetDatabaseIndex = index;
                return true;
            }
        });
        /** @type {any} */ let targetTableIndex;
        let targetTable = targetDatabase[0].tables.filter((tableObject, index)=>{
            if (tableObject?.tableName === table_slug) {
                targetTableIndex = index;
                return true;
            }
        });
        if (targetTable[0].childTable) {
            const parentDb = userSchemaData.filter((db)=>db.dbFullName === targetTable[0].childTableDbFullName)[0];
            const parentTableObject = parentDb.tables.filter((table)=>{
                if (table.tableName === targetTable[0].childTableName) {
                    return true;
                }
            })[0];
            let targetChildIndex;
            const parentTableChildObject = parentTableObject.childrenTables?.filter((childTable, index)=>{
                if (childTable.tableName === table_slug) {
                    targetChildIndex = index;
                }
            });
            if (typeof targetChildIndex === "number") parentTableObject.childrenTables?.splice(targetChildIndex, 1);
        }
        targetDatabase[0].tables.splice(targetTableIndex, 1);
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        /**
         * Check Children Databases
         *
         * @description Check Children Databases
         */ if (targetDatabase[0].childrenDatabases) {
            for(let i = 0; i < targetDatabase[0].childrenDatabases.length; i++){
                const childDb = targetDatabase[0].childrenDatabases[i];
                try {
                    const targetChild = userSchemaData.filter((db)=>db.dbFullName === childDb.dbFullName)[0];
                    targetChild.tables = targetDatabase[0].tables;
                    await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(`DELETE FROM user_database_tables WHERE table_slug=? AND user_id=? AND db_slug=?`, [
                        table_slug,
                        user.id,
                        targetChild.dbSlug
                    ]);
                } catch (/** @type {any} */ error) {
                    _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
                        component: "/api/deleteUserTable/lines-125-128",
                        message: error.message,
                        user: user
                    });
                }
            }
        }
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        fs.writeFileSync(`${userSchemaMainFilePath}`, JSON.stringify(userSchemaData), "utf8");
        ////////////////////////////////////////
        res.json({
            success: true
        });
    ////////////////////////////////////////
    } catch (/** @type {any} */ error1) {
        ////////////////////////////////////////
        _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
            component: "/api/deleteUserTable/main-catch-error",
            message: error1.message,
            user: user
        });
        res.json({
            success: false,
            msg: "File Updates Failed"
        });
    }
}


/***/ })

};
;

// 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,8326,1311], () => (__webpack_exec__(6772)));
module.exports = __webpack_exports__;

})();