"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 });
const path_1 = __importDefault(require("path"));
require("dotenv").config({ path: "../../../.env" });
const fs_1 = __importDefault(require("fs"));
const ejson_1 = __importDefault(require("../../../utils/ejson"));
const hashPassword_1 = __importDefault(require("../../../functions/dsql/hashPassword"));
const updateDbEntry_1 = __importDefault(require("../../../functions/backend/db/updateDbEntry"));
const tmpDir = process.argv[process.argv.length - 1];
/**
 * # Create New User
 */
function createUser() {
    return __awaiter(this, void 0, void 0, function* () {
        /**
         * Validate Form
         *
         * @description Check if request body is valid
         */
        try {
            const isTmpDir = Boolean(tmpDir === null || tmpDir === void 0 ? void 0 : tmpDir.match(/\.json$/));
            const targetPath = isTmpDir
                ? path_1.default.resolve(process.cwd(), tmpDir)
                : path_1.default.resolve(__dirname, "./update-user.json");
            const updateUserObj = ejson_1.default.parse(fs_1.default.readFileSync(targetPath, "utf-8"));
            if (typeof updateUserObj !== "object" || Array.isArray(updateUserObj))
                throw new Error("Update User Object Invalid!");
            let hashedPassword = updateUserObj.password
                ? (0, hashPassword_1.default)({
                    encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD || "",
                    password: updateUserObj.password,
                })
                : undefined;
            let updatePayload = Object.assign({}, updateUserObj);
            if (hashedPassword) {
                updatePayload["password"] = hashedPassword;
            }
            const newUser = yield (0, updateDbEntry_1.default)({
                dbFullName: "datasquirel",
                tableName: "users",
                data: Object.assign(Object.assign({}, updatePayload), { id: undefined }),
                identifierColumnName: "id",
                identifierValue: updatePayload.id,
            });
            if (!(newUser === null || newUser === void 0 ? void 0 : newUser.affectedRows))
                return false;
            if (isTmpDir) {
                try {
                    fs_1.default.unlinkSync(path_1.default.resolve(process.cwd(), tmpDir));
                }
                catch (error) { }
            }
            return true;
        }
        catch (error) {
            console.log(`Error in creating user => ${error.message}`);
            return false;
        }
    });
}
createUser().then((res) => {
    if (res) {
        console.log("User Update Success!!!");
    }
    else {
        console.log("User Update Failed!");
    }
    process.exit();
});