import CryptoJS from 'crypto-js'

class CryptToJS {
    private crypt: typeof CryptoJS
    private secret: string
    private key: CryptoJS.lib.WordArray
    private iv: CryptoJS.lib.WordArray

    constructor() {
        this.crypt = CryptoJS
        this.secret = 'Believe in yourself.'
        this.key = CryptoJS.enc.Utf8.parse(this.secret)
        this.iv = CryptoJS.enc.Utf8.parse(this.secret.slice(0, 16))
    }

    public encrypt(text: string): string {
        const encrypted = this.crypt.AES.encrypt(text, this.key, {
            iv: this.iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
        return encrypted.toString()
    }

    public decrypt(text: string): string {
        if (!text) return ''
        const decrypted = this.crypt.AES.decrypt(text, this.key, {
            iv: this.iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
        return decrypted.toString(CryptoJS.enc.Utf8)
    }
}

export default new CryptToJS()
