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

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

module.exports = require("lodash");

/***/ }),

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

/***/ }),

/***/ 7840:
/***/ ((__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 _functions_backend_grabUserSchemaData__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8164);
/* 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 lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6517);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2224);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_4__);
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ const fs = __webpack_require__(7147);
const path = __webpack_require__(1017);
const { execSync  } = __webpack_require__(2081);





/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * @typedef {object} SyncTableBodySrcDstObject
 * @property {string} db
 * @property {string} table
 */ /**
 * @typedef {object} SyncTableBody
 * @property {"Pull" | "Push"} paradigm
 * @property {SyncTableBodySrcDstObject} src
 * @property {SyncTableBodySrcDstObject} dst
 * @property {any} [delegated]
 */ /**
 * API handler
 * ==============================================================================
 * @type {import("next").NextApiHandler}
 */ async function handler(req, res) {
    /**
     * Check method
     *
     * @description Check request method and return if invalid
     */ if (req.method !== "GET") return res.json({
        msg: "Failed!"
    });
    /**
     * User auth
     *
     * @description Authenticate user
     */ const user = await _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_2___default()(req, res);
    if (!user) {
        return res.json({
            success: false,
            msg: "Unauthorized"
        });
    }
    const dbUserId = req.query.dbUserId;
    const delegated = req.query.delegated;
    /**
     * Send Response
     *
     * @description Send a boolean response
     */ try {
        if (!dbUserId) {
            throw new Error("No Root user Id Found!");
        }
        /** @type {import("@/package-shared/types").MYSQL_delegated_user_tables_table_def[]} */ const delegatedTables = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_4___default()(`SELECT * FROM datasquirel.delegated_user_tables WHERE delegated_user_id=? AND root_user_id=?`, [
            String(user.id),
            String(dbUserId)
        ]);
        const rootUserDbSchema = (0,_functions_backend_grabUserSchemaData__WEBPACK_IMPORTED_MODULE_0__["default"])({
            userId: String(dbUserId)
        });
        if (!rootUserDbSchema) {
            throw new Error("Root user schema not found!");
        }
        /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} */ const filteredDbSchema = [];
        delegatedTables.forEach((tblObj)=>{
            const existingDbIndex = filteredDbSchema.findIndex((db)=>db.dbSlug === tblObj.database);
            /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType | undefined} */ const targetDb = rootUserDbSchema.find((db)=>db.dbSlug === tblObj.database);
            if (targetDb) {
                /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType} */ const finalDb = filteredDbSchema[existingDbIndex] ? filteredDbSchema[existingDbIndex] : {
                    ...targetDb,
                    tables: []
                };
                const targetDbTbls = lodash__WEBPACK_IMPORTED_MODULE_3___default().cloneDeep(targetDb.tables);
                const targetTable = targetDbTbls.find((tbl)=>tbl.tableName === tblObj.table);
                if (targetTable && filteredDbSchema[existingDbIndex]) {
                    filteredDbSchema[existingDbIndex] = {
                        ...finalDb,
                        tables: [
                            ...filteredDbSchema[existingDbIndex].tables,
                            targetTable, 
                        ]
                    };
                } else if (targetTable && !filteredDbSchema[existingDbIndex]) {
                    filteredDbSchema.push({
                        ...targetDb,
                        tables: [
                            targetTable
                        ]
                    });
                }
            }
        });
        ////////////////////////////////////////
        res.json({
            success: true,
            payload: filteredDbSchema
        });
    } catch (/** @type {any} */ error) {
        console.log("ERROR:", error.message);
        ////////////////////////////////////////
        _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
            component: "/api/get-authorized-databases",
            message: error.message,
            user: user
        });
        res.json({
            success: false,
            msg: error.message
        });
    ////////////////////////////////////////
    }
}


/***/ })

};
;

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

})();