"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 = updateDbEntry;
const sanitize_html_1 = __importDefault(require("sanitize-html"));
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
const check_if_is_master_1 = __importDefault(require("../../../utils/check-if-is-master"));
const conn_db_handler_1 = __importDefault(require("../../../utils/db/conn-db-handler"));
/**
 * # Update DB Function
 * @description
 */
function updateDbEntry(_a) {
    return __awaiter(this, arguments, void 0, function* ({ dbContext, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, forceLocal, }) {
        var _b;
        /**
         * Check if data is valid
         */
        if (!data || !Object.keys(data).length)
            return null;
        const isMaster = forceLocal
            ? true
            : (0, check_if_is_master_1.default)({ dbContext, dbFullName });
        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;
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        /**
         * Declare variables
         *
         * @description Declare "results" variable
         */
        const dataKeys = Object.keys(data);
        let updateKeyValueArray = [];
        let updateValues = [];
        for (let i = 0; i < dataKeys.length; i++) {
            try {
                const dataKey = dataKeys[i];
                // @ts-ignore
                let value = 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;
                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.encrypted) {
                    value = (0, encrypt_1.default)({
                        data: value,
                        encryptionKey,
                        encryptionSalt,
                    });
                }
                if (typeof value === "object") {
                    value = JSON.stringify(value);
                }
                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 = "";
                    }
                }
                if (typeof value === "string" && value.match(/^null$/i)) {
                    value = {
                        toSqlString: function () {
                            return "NULL";
                        },
                    };
                }
                if (typeof value === "string" && !value.match(/./i)) {
                    value = {
                        toSqlString: function () {
                            return "NULL";
                        },
                    };
                }
                updateKeyValueArray.push(`\`${dataKey}\`=?`);
                if (typeof value == "number") {
                    updateValues.push(String(value));
                }
                else {
                    updateValues.push(value);
                }
                ////////////////////////////////////////
                ////////////////////////////////////////
            }
            catch ( /** @type {any} */error) {
                ////////////////////////////////////////
                ////////////////////////////////////////
                console.log("DSQL: Error in parsing data keys in update function =>", error.message);
                continue;
            }
        }
        ////////////////////////////////////////
        ////////////////////////////////////////
        updateKeyValueArray.push(`date_updated='${Date()}'`);
        updateKeyValueArray.push(`date_updated_code='${Date.now()}'`);
        ////////////////////////////////////////
        ////////////////////////////////////////
        const query = `UPDATE ${isMaster ? "" : `\`${dbFullName}\`.`}\`${tableName}\` SET ${updateKeyValueArray.join(",")} WHERE \`${identifierColumnName}\`=?`;
        updateValues.push(identifierValue);
        const updatedEntry = yield (0, conn_db_handler_1.default)(DB_CONN, query, updateValues);
        /**
         * Return statement
         */
        return updatedEntry;
    });
}