import CryptoJS from 'crypto-js'

const ENCRYPTION_KEY = process.env.APP_ENCRYPTION_KEY! // NOT public

if (!ENCRYPTION_KEY) {
    throw new Error('APP_ENCRYPTION_KEY is not set')
}

export function decryptServer(cipherText: string): string | any {
    try {
        const bytes = CryptoJS.AES.decrypt(cipherText, ENCRYPTION_KEY)
        const decrypted = bytes.toString(CryptoJS.enc.Utf8)

        if (!decrypted) {
            throw new Error('Invalid or corrupted ciphertext')
        }

        return decrypted
    } catch (error) {
        console.error('Decryption failed:', error)
        return ''
    }
}
