// @ts-check

import { scryptSync, createDecipheriv } from "crypto";
import { Buffer } from "buffer";

type Param = {
    encryptedString: string;
    encryptionKey?: string;
    encryptionSalt?: string;
};

/**
 * # Decrypt Function
 */
export default function decrypt({
    encryptedString,
    encryptionKey,
    encryptionSalt,
}: Param) {
    if (!encryptedString?.match(/./)) {
        console.log("Encrypted string is invalid");
        return encryptedString;
    }

    const finalEncryptionKey =
        encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
    const finalEncryptionSalt =
        encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
    const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
        ? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
        : 24;

    if (!finalEncryptionKey?.match(/.{8,}/)) {
        console.log("Decrption key is invalid");
        return encryptedString;
    }

    if (!finalEncryptionSalt?.match(/.{8,}/)) {
        console.log("Decrption salt is invalid");
        return encryptedString;
    }

    const algorithm = "aes-192-cbc";

    let key = scryptSync(finalEncryptionKey, finalEncryptionSalt, finalKeyLen);
    let iv = Buffer.alloc(16, 0);

    const decipher = createDecipheriv(algorithm, key, iv);

    try {
        let decrypted = decipher.update(encryptedString, "hex", "utf8");
        decrypted += decipher.final("utf8");
        return decrypted;
    } catch (error: any) {
        console.log("Error in decrypting =>", error.message);
        return encryptedString;
    }
}