"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 DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
/**
 * # Update DB Function
 * @description
 */
function updateDbEntry(_a) {
    return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }) {
        var _b;
        /**
         * Check if data is valid
         */
        if (!data || !Object.keys(data).length)
            return null;
        const isMaster = useLocal
            ? true
            : (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
                ? false
                : dbFullName && !dbFullName.match(/^datasquirel$/)
                    ? false
                    : true;
        /** @type {(a1:any, a2?:any)=> any } */
        const dbHandler = useLocal
            ? LOCAL_DB_HANDLER_1.default
            : isMaster
                ? DB_HANDLER_1.default
                : DSQL_USER_DB_HANDLER_1.default;
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        /**
         * 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 \`${dbFullName}\`.\`${tableName}\` SET ${updateKeyValueArray.join(",")} WHERE \`${identifierColumnName}\`=?`;
        updateValues.push(identifierValue);
        const updatedEntry = isMaster
            ? yield dbHandler(query, updateValues)
            : yield dbHandler({
                paradigm,
                queryString: query,
                queryValues: updateValues,
            });
        /**
         * Return statement
         */
        return updatedEntry;
    });
}