// @ts-check

import { scryptSync, createDecipheriv } from "crypto";
import { Buffer } from "buffer";
import grabKeys from "../../utils/grab-keys";

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 {
        key: encrptKey,
        salt,
        keyLen,
        algorithm,
        bufferAllocSize,
    } = grabKeys({ encryptionKey });

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

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

    let key = scryptSync(encrptKey, salt, keyLen);
    let iv = Buffer.alloc(bufferAllocSize, 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);
        global.ERROR_CALLBACK?.(`Error Decrypting data`, error as Error);
        return encryptedString;
    }
}