"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = addDbEntry;
const sanitize_html_1 = __importDefault(require("sanitize-html"));
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
const updateDbEntry_1 = __importDefault(require("./updateDbEntry"));
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
const conn_db_handler_1 = __importDefault(require("../../../utils/db/conn-db-handler"));
const check_if_is_master_1 = __importDefault(require("../../../utils/check-if-is-master"));
const debug_log_1 = __importDefault(require("../../../utils/logging/debug-log"));
/**
 * Add a db Entry Function
 */
function addDbEntry(_a) {
    return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, forceLocal, debug, }) {
        var _b, _c, _d;
        /**
         * Initialize variables
         */
        const isMaster = forceLocal
            ? true
            : (0, check_if_is_master_1.default)({ dbContext, dbFullName });
        if (debug) {
            (0, debug_log_1.default)({
                log: isMaster,
                addTime: true,
                label: "isMaster",
            });
        }
        const DB_CONN = isMaster
            ? global.DSQL_DB_CONN
            : global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
        const DB_RO_CONN = isMaster
            ? global.DSQL_DB_CONN
            : global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN;
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        if (data === null || data === void 0 ? void 0 : data["date_created_timestamp"])
            delete data["date_created_timestamp"];
        if (data === null || data === void 0 ? void 0 : data["date_updated_timestamp"])
            delete data["date_updated_timestamp"];
        if (data === null || data === void 0 ? void 0 : data["date_updated"])
            delete data["date_updated"];
        if (data === null || data === void 0 ? void 0 : data["date_updated_code"])
            delete data["date_updated_code"];
        if (data === null || data === void 0 ? void 0 : data["date_created"])
            delete data["date_created"];
        if (data === null || data === void 0 ? void 0 : data["date_created_code"])
            delete data["date_created_code"];
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        if (duplicateColumnName && typeof duplicateColumnName === "string") {
            const checkDuplicateQuery = `SELECT * FROM ${isMaster ? "" : `\`${dbFullName}\`.`}\`${tableName}\` WHERE \`${duplicateColumnName}\`=?`;
            const duplicateValue = yield (0, conn_db_handler_1.default)(DB_RO_CONN, checkDuplicateQuery, [duplicateColumnValue]);
            if ((duplicateValue === null || duplicateValue === void 0 ? void 0 : duplicateValue[0]) && !update) {
                return null;
            }
            else if (duplicateValue && duplicateValue[0] && update) {
                return yield (0, updateDbEntry_1.default)({
                    dbContext,
                    dbFullName,
                    tableName,
                    data,
                    tableSchema,
                    encryptionKey,
                    encryptionSalt,
                    identifierColumnName: duplicateColumnName,
                    identifierValue: duplicateColumnValue || "",
                });
            }
        }
        /**
         * Declare variables
         *
         * @description Declare "results" variable
         */
        const dataKeys = Object.keys(data);
        let insertKeysArray = [];
        let insertValuesArray = [];
        for (let i = 0; i < dataKeys.length; i++) {
            try {
                const dataKey = dataKeys[i];
                // @ts-ignore
                let value = data === null || data === void 0 ? void 0 : data[dataKey];
                const targetFieldSchemaArray = tableSchema
                    ? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName == dataKey)
                    : null;
                const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
                    ? targetFieldSchemaArray[0]
                    : null;
                if (value == null || value == undefined)
                    continue;
                if (((_c = targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.dataType) === null || _c === void 0 ? void 0 : _c.match(/int$/i)) &&
                    typeof value == "string" &&
                    !(value === null || value === void 0 ? void 0 : value.match(/./)))
                    continue;
                if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
                    value = (0, encrypt_1.default)({
                        data: value,
                        encryptionKey,
                        encryptionSalt,
                    });
                    console.log("DSQL: Encrypted value =>", value);
                }
                const htmlRegex = /<[^>]+>/g;
                if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) {
                    value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default);
                }
                if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
                    const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
                    if (!pattern.test(value)) {
                        console.log("DSQL: Pattern not matched =>", value);
                        value = "";
                    }
                }
                insertKeysArray.push("`" + dataKey + "`");
                if (typeof value === "object") {
                    value = JSON.stringify(value);
                }
                if (typeof value == "number") {
                    insertValuesArray.push(String(value));
                }
                else {
                    insertValuesArray.push(value);
                }
            }
            catch (error) {
                console.log("DSQL: Error in parsing data keys =>", error.message);
                (_d = global.ERROR_CALLBACK) === null || _d === void 0 ? void 0 : _d.call(global, `Error parsing Data Keys`, error);
                continue;
            }
        }
        ////////////////////////////////////////
        if (!(data === null || data === void 0 ? void 0 : data["date_created"])) {
            insertKeysArray.push("`date_created`");
            insertValuesArray.push(Date());
        }
        if (!(data === null || data === void 0 ? void 0 : data["date_created_code"])) {
            insertKeysArray.push("`date_created_code`");
            insertValuesArray.push(Date.now());
        }
        ////////////////////////////////////////
        if (!(data === null || data === void 0 ? void 0 : data["date_updated"])) {
            insertKeysArray.push("`date_updated`");
            insertValuesArray.push(Date());
        }
        if (!(data === null || data === void 0 ? void 0 : data["date_updated_code"])) {
            insertKeysArray.push("`date_updated_code`");
            insertValuesArray.push(Date.now());
        }
        ////////////////////////////////////////
        const query = `INSERT INTO ${isMaster ? "" : `\`${dbFullName}\`.`}\`${tableName}\` (${insertKeysArray.join(",")}) VALUES (${insertValuesArray
            .map(() => "?")
            .join(",")})`;
        const queryValuesArray = insertValuesArray;
        if (debug) {
            (0, debug_log_1.default)({
                log: DB_CONN === null || DB_CONN === void 0 ? void 0 : DB_CONN.getConfig(),
                addTime: true,
                label: "DB_CONN Config",
            });
            (0, debug_log_1.default)({
                log: query,
                addTime: true,
                label: "query",
            });
            (0, debug_log_1.default)({
                log: queryValuesArray,
                addTime: true,
                label: "queryValuesArray",
            });
        }
        const newInsert = yield (0, conn_db_handler_1.default)(DB_CONN, query, queryValuesArray, debug);
        if (debug) {
            (0, debug_log_1.default)({
                log: newInsert,
                addTime: true,
                label: "newInsert",
            });
        }
        /**
         * Return statement
         */
        return newInsert;
    });
}