// @ts-check

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

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

/**
 * # Encrypt String
 */
export default function encrypt({
    data,
    encryptionKey,
    encryptionSalt,
}: Param): string | null {
    if (!data?.match(/./)) {
        console.log("Encryption string is invalid");
        return data;
    }

    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("Encryption key is invalid");
        return data;
    }
    if (!finalEncryptionSalt?.match(/.{8,}/)) {
        console.log("Encryption salt is invalid");
        return data;
    }

    const algorithm = "aes-192-cbc";
    const password = finalEncryptionKey;

    let key = scryptSync(password, finalEncryptionSalt, finalKeyLen);
    let iv = Buffer.alloc(16, 0);
    // @ts-ignore
    const cipher = createCipheriv(algorithm, key, iv);

    try {
        let encrypted = cipher.update(data, "utf8", "hex");
        encrypted += cipher.final("hex");
        return encrypted;
    } catch (/** @type {*} */ error: any) {
        console.log("Error in encrypting =>", error.message);
        return data;
    }
}