import path from "path";
require("dotenv").config({ path: "../../../.env" });
import fs from "fs";
import EJSON from "../../../utils/ejson";
import hashPassword from "../../../functions/dsql/hashPassword";
import updateDbEntry from "../../../functions/backend/db/updateDbEntry";

const tmpDir = process.argv[process.argv.length - 1];

/**
 * # Create New User
 */
async function createUser() {
    /**
     * Validate Form
     *
     * @description Check if request body is valid
     */
    try {
        const isTmpDir = Boolean(tmpDir?.match(/\.json$/));
        const targetPath = isTmpDir
            ? path.resolve(process.cwd(), tmpDir)
            : path.resolve(__dirname, "./update-user.json");
        const updateUserObj = EJSON.parse(fs.readFileSync(targetPath, "utf-8"));

        if (typeof updateUserObj !== "object" || Array.isArray(updateUserObj))
            throw new Error("Update User Object Invalid!");

        let hashedPassword = updateUserObj.password
            ? hashPassword({
                  encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD || "",
                  password: updateUserObj.password,
              })
            : undefined;

        let updatePayload = { ...updateUserObj };
        if (hashedPassword) {
            updatePayload["password"] = hashedPassword;
        }

        const newUser: any = await updateDbEntry({
            dbFullName: "datasquirel",
            tableName: "users",
            data: { ...updatePayload, id: undefined },
            identifierColumnName: "id",
            identifierValue: updatePayload.id,
        });

        if (!newUser?.affectedRows) return false;

        if (isTmpDir) {
            try {
                fs.unlinkSync(path.resolve(process.cwd(), tmpDir));
            } catch (error) {}
        }

        return true;
    } catch (error: any) {
        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();
});