"use strict";
// @ts-check
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 = apiUpdateUser;
const updateDbEntry_1 = __importDefault(require("../../backend/db/updateDbEntry"));
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
/**
 * # Update API User Function
 */
function apiUpdateUser(_a) {
    return __awaiter(this, arguments, void 0, function* ({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }) {
        const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
        const existingUserValues = [updatedUserId];
        const existingUser = yield (0, varDatabaseDbHandler_1.default)({
            queryString: existingUserQuery,
            queryValuesArray: existingUserValues,
            database: dbFullName,
            useLocal,
        });
        if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
            return {
                success: false,
                msg: "User not found",
            };
        }
        const data = (() => {
            const reqBodyKeys = Object.keys(payload);
            const targetTableSchema = (() => {
                var _a;
                try {
                    const targetDatabaseSchema = (_a = dbSchema === null || dbSchema === void 0 ? void 0 : dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((tbl) => tbl.tableName == "users");
                    return targetDatabaseSchema;
                }
                catch (error) {
                    return undefined;
                }
            })();
            /** @type {any} */
            const finalData = {};
            reqBodyKeys.forEach((key) => {
                var _a;
                const targetFieldSchema = (_a = targetTableSchema === null || targetTableSchema === void 0 ? void 0 : targetTableSchema.fields) === null || _a === void 0 ? void 0 : _a.find((field) => field.fieldName == key);
                if (key === null || key === void 0 ? void 0 : key.match(/^date_|^id$|^uuid$/))
                    return;
                let value = payload[key];
                if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
                    value = (0, encrypt_1.default)({ data: value });
                }
                finalData[key] = value;
            });
            if (finalData.password && typeof finalData.password == "string") {
                finalData.password = (0, hashPassword_1.default)({ password: finalData.password });
            }
            return finalData;
        })();
        const updateUser = yield (0, updateDbEntry_1.default)({
            dbContext: "Dsql User",
            paradigm: "Full Access",
            dbFullName,
            tableName: "users",
            identifierColumnName: "id",
            identifierValue: updatedUserId,
            data: data,
            useLocal,
        });
        return {
            success: true,
            payload: updateUser,
        };
    });
}