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

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

module.exports = require("datasquirel/functions/hashPassword");

/***/ }),

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

module.exports = require("generate-password");

/***/ }),

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

module.exports = require("lodash");

/***/ }),

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

module.exports = require("nodemailer");

/***/ }),

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

/***/ }),

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

module.exports = require("path");

/***/ }),

/***/ 6142:
/***/ ((__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_encrypt__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7547);
/* harmony import */ var _package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _functions_backend_handleNodemailer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6926);
/* harmony import */ var _functions_backend_handleNodemailer__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_handleNodemailer__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var datasquirel_functions_hashPassword__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2029);
/* harmony import */ var datasquirel_functions_hashPassword__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(datasquirel_functions_hashPassword__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 path__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1017);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2081);
/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _package_shared_functions_backend_addMariadbUser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4294);
/* harmony import */ var _package_shared_functions_backend_addMariadbUser__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_addMariadbUser__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(2224);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(5338);
/* harmony import */ var _package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _package_shared_functions_backend_db_updateDbEntry__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(5886);
/* harmony import */ var _package_shared_functions_backend_db_updateDbEntry__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_db_updateDbEntry__WEBPACK_IMPORTED_MODULE_9__);
// @ts-check
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({
        user: null,
        msg: "Registration Failed!"
    });
    /**
     * Validate Form
     *
     * @description Check if request body is valid
     */ const sanitizedReqBody = req.body;
    const { inviteObject  } = sanitizedReqBody;
    const first_name = sanitizedReqBody.first_name;
    const last_name = sanitizedReqBody.last_name;
    const email = sanitizedReqBody.email;
    const password = sanitizedReqBody.password;
    const username = sanitizedReqBody.username;
    if (!email.match(/.*@.*\..*/)) return res.json({
        user: null,
        msg: "Invalid Email"
    });
    if (!first_name.match(/^[a-zA-Z]+$/) || !last_name.match(/^[a-zA-Z]+$/)) return res.json({
        user: null,
        msg: "Invalid Name"
    });
    if (password?.match(/ /)) return res.json({
        user: null,
        msg: "Invalid Password"
    });
    if (username?.match(/ /)) return res.json({
        user: null,
        msg: "Invalid Username"
    });
    /**
     * Validate Form
     *
     * @description Check if request body is valid
     */ try {
        /** ********************* Hash Password */ let hashedPassword = datasquirel_functions_hashPassword__WEBPACK_IMPORTED_MODULE_2___default()({
            encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD || "",
            password: password
        });
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        let existingUser = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_7___default()(`SELECT * FROM users WHERE email='${email}'`);
        if (existingUser && existingUser[0]) return res.json({
            user: null,
            msg: "User Already Exists"
        });
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        const newUser = await _package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_8___default()({
            dbFullName: "datasquirel",
            tableName: "users",
            data: {
                first_name,
                last_name,
                email,
                password: hashedPassword,
                username
            }
        });
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        // console.log(response);
        if (!newUser?.insertId) return res.json({
            user: null,
            msg: "Adding User to Database failed"
        });
        /**
         * Add a Mariadb User for this User
         */ await _package_shared_functions_backend_addMariadbUser__WEBPACK_IMPORTED_MODULE_6___default()({
            userId: newUser.insertId
        });
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        /**
         * Create new Stripe customer
         *
         * @description Create a new stripe customer
         */ // let newStripeCustomer = await handlePayments(
        //     "create_customer",
        //     {
        //         email: email,
        //         name: first_name + " " + last_name,
        //         description: "Agent user",
        //     },
        //     {
        //         id: newUser.insertId,
        //         email: email,
        //         first_name: first_name,
        //         user_type: "agents",
        //     }
        // );
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        /**
         * Send email Verification
         *
         * @description Send verification email to newly created agent
         */ let generatedToken = _package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_0___default()(JSON.stringify({
            id: newUser.insertId,
            email: email,
            dateCode: Date.now()
        }));
        _functions_backend_handleNodemailer__WEBPACK_IMPORTED_MODULE_1___default()({
            to: email,
            subject: "Verify Email Address",
            text: "Please click the link to verify your email address",
            html: fs.readFileSync("./email/send-email-verification-link.html", "utf8").replace(/{{host}}/, process.env.DSQL_HOST || "").replace(/{{token}}/, generatedToken || "")
        }).then((mail)=>{
        // console.log("User verification email =>", mail);
        });
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        const isProduction = "production".match(/production/);
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        let userImageName = `users_${newUser.insertId}.jpg`;
        let userImageTnumbnailName = `users_${newUser.insertId}_thumbnail.jpg`;
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        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");
        }
        /**
         * Create new user folder and file
         *
         * @description Create new user folder and file
         */ let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`;
        let newUserMediaFolderPath = path__WEBPACK_IMPORTED_MODULE_4___default().join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
        fs.mkdirSync(newUserSchemaFolderPath, {
            recursive: true
        });
        fs.mkdirSync(newUserMediaFolderPath, {
            recursive: true
        });
        fs.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        let imagePath = path__WEBPACK_IMPORTED_MODULE_4___default().join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}/user-${newUser.insertId}-profile.jpg`);
        let imageThumbnailPath = path__WEBPACK_IMPORTED_MODULE_4___default().join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}/user-${newUser.insertId}-profile-thumbnail.jpg`);
        let prodImageUrl = imagePath.replace(STATIC_ROOT, process.env.DSQL_STATIC_HOST || "");
        let prodImageThumbnailUrl = imageThumbnailPath.replace(STATIC_ROOT, process.env.DSQL_STATIC_HOST || "");
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        fs.copyFileSync("./public/images/user-preset.png", imagePath);
        fs.copyFileSync("./public/images/user-preset-thumbnail.png", imageThumbnailPath);
        (0,child_process__WEBPACK_IMPORTED_MODULE_5__.execSync)(`chmod 644 ${imagePath} ${imageThumbnailPath}`);
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        const updateImages = await _package_shared_functions_backend_db_updateDbEntry__WEBPACK_IMPORTED_MODULE_9___default()({
            dbFullName: "datasquirel",
            tableName: "users",
            identifierColumnName: "id",
            identifierValue: newUser.insertId,
            data: {
                image: prodImageUrl,
                image_thumbnail: prodImageThumbnailUrl
            }
        });
        // await global.DB_HANDLER(`
        //     UPDATE
        //         users
        //     SET
        //         image='${isProduction ? prodImageUrl : imagePath.replace(/^\.\/public/, "")}',
        //         image_thumbnail='${isProduction ? prodImageThumbnailUrl : imageThumbnailPath.replace(/^\.\/public/, "")}'
        //     WHERE
        //         id='${newUser.insertId}'
        // `);
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        if (inviteObject) {
            const newUserUser = await _package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_8___default()({
                dbFullName: "datasquirel",
                tableName: "user_users",
                data: {
                    user_id: inviteObject.invite,
                    invited_user_id: newUser.insertId,
                    database_access: inviteObject.database_access,
                    user_priviledge: inviteObject.priviledge,
                    user_type: "admin",
                    first_name,
                    last_name,
                    email,
                    username,
                    image: prodImageUrl,
                    image_thumbnail: prodImageThumbnailUrl
                }
            });
            const inviteAccepted = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_7___default()(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [
                inviteObject.invite,
                email
            ]);
            const dbTableData = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_7___default()(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [
                inviteObject.invite,
                email
            ]);
            const clearEntries = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_7___default()(`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`, [
                inviteObject.invite,
                newUserUser.insertId
            ]);
            if (dbTableData && dbTableData[0]) {
                const dbTableEntries = dbTableData[0].db_tables_data.split("|");
                for(let i = 0; i < dbTableEntries.length; i++){
                    const dbTableEntry = dbTableEntries[i];
                    const dbTableEntryArray = dbTableEntry.split("-");
                    const [db_slug, table_slug] = dbTableEntryArray;
                    const newEntry = await _package_shared_functions_backend_db_addDbEntry__WEBPACK_IMPORTED_MODULE_8___default()({
                        dbFullName: "datasquirel",
                        tableName: "delegated_user_tables",
                        data: {
                            delegated_user_id: newUserUser.insertId,
                            root_user_id: inviteObject.invite,
                            database: db_slug,
                            table: table_slug,
                            priviledge: inviteObject.priviledge
                        }
                    });
                }
            }
        }
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        res.json(newUser);
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    } catch (/** @type {any} */ error) {
        console.log(`Error in creating user => ${error.message}`);
        _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_3___default()({
            component: "/api/registerUser/main-catch-error",
            message: error.message,
            user: {
                first_name,
                last_name,
                email
            }
        });
        res.json({
            user: null
        });
    }
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}


/***/ })

};
;

// 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,3017,3403,7547,5886,5338,6926,7487,4294], () => (__webpack_exec__(6142)));
module.exports = __webpack_exports__;

})();