const crypto = require('crypto')

const KEY_STR = "Wet2C8d34f62ndi3"
const IV_STR = "K6iv85jBD8jgf32D"
const SALT = "rDJiNB9j7vD2"

const KEY = Buffer.from(KEY_STR, 'utf-8')
const IV = Buffer.from(IV_STR, 'utf-8')

/**
 * AES 加密
 */
function dataEncrypt(plainText) {
    try {
        const cipher = crypto.createCipheriv('aes-128-cbc', KEY, IV)
        cipher.setAutoPadding(true)

        let encrypted = cipher.update(plainText, 'utf-8')
        encrypted = Buffer.concat([encrypted, cipher.final()])

        return encrypted.toString('base64')
    } catch (err) {
        console.error('加密失败:', err.message)
        return null
    }
}

/**
 * AES 解密
 */
function dataDecrypt(encryptedBase64Text) {
    try {
        const encryptedBuffer = Buffer.from(encryptedBase64Text, 'base64')

        const decipher = crypto.createDecipheriv('aes-128-cbc', KEY, IV)
        decipher.setAutoPadding(true)

        let decrypted = decipher.update(encryptedBuffer)
        decrypted = Buffer.concat([decrypted, decipher.final()])

        return decrypted.toString('utf-8')
    } catch (err) {
        console.error('解密失败:', err.message)
        return null
    }
}

/**
 * MD5 签名
 */
function dataSign(dataObj) {
    if (typeof dataObj !== 'object') {
        throw new TypeError('data must be object')
    }

    const sortedKeys = Object.keys(dataObj).sort()

    let str = ''
    for (const key of sortedKeys) {
        str += key + String(dataObj[key])
    }

    str += SALT

    return crypto.createHash('md5').update(str, 'utf-8').digest('hex')
}

/**
 * OSS POST 签名
 */
function ossPostSign(accessKeySecret, policyDocument) {
    const policyStr = JSON.stringify(policyDocument)

    const base64Policy = Buffer.from(policyStr).toString('base64')

    const signature = crypto
        .createHmac('sha1', accessKeySecret)
        .update(base64Policy)
        .digest('base64')

    return [base64Policy, signature]
}

module.exports = {
    dataEncrypt,
    dataDecrypt,
    dataSign,
    ossPostSign
}