// ==========================================================================
// 所属模块：lib - responseWriter
// 生成日期：2024-02-19 00:24:00 +0800 CST
// 生成路径: lib/responseWriter.js
// 生成人：Cato
// 功能描述：用于全局的请求返回消息结构体的构建。（注册于global.js内)
// ==========================================================================

const compress = require('compress')

// 构建成功返回
function okMsg(data) {
    let res = {
        "status": 0,
        "msg": 'success',
        "data": data
    }

    log(1, JSON.stringify(res))

    let userToken = payload.get().headers["Authorization"] || payload.get().query["token"] || payload.get().headers["X-Token"] || (payload.get().cookies ? payload.get().cookie["token"] : null);
    var signature = `${payload.get().method}:${payload.get().host}:${payload.get().url}::${payload.get().url}:${userToken}:${payload.get().body ? payload.get().body.toString() : '>'}`
    signature = crypto.hash.md5(signature).toHEX.encoding().toString()
    // 检查缓存
    if (!TABLE_INFO.cache_life) {
        TABLE_INFO.cache_life = 5
    }

    // console.log(JSON.stringify(APP_INFO));

    if (APP_INFO) {
        switch (APP_INFO.status) {
            case 3:
                res = crypto.sm4.encrypt('CBC', APP_INFO.secret.split('').reverse().join(''), JSON.stringify(res), APP_INFO.secret).toBase64.url.encoding().toString()
            case 2:
                // console.log(APP_INFO.secret)
                // console.log(APP_INFO.secret.split('').reverse().join(''))
                res.ciphertext = crypto.sm4.encrypt('CBC', APP_INFO.secret.split('').reverse().join(''), JSON.stringify(res), APP_INFO.secret).toBase64.url.encoding().toString()
        }
    }

    // 如果请求头中包含 Accept-Encoding 并且 Accept-Encoding 的值包含 br，则设置 Content-Encoding 为 br。
    if (payload.get().headers['Accept-Encoding'] && payload.get().headers['Accept-Encoding'][0].includes('br')) {
        response.headers.set("Content-Encoding", 'br')
        res = compress.brotli.compress(res).toString()

        'use api/lib/setResponseCache.js'
        response.write(res)
        return res
    }

    res = JSON.stringify(res)

    'use api/lib/setResponseCache.js'
    response.write(res)
    return res
}

// 构建错误返回
function errMsg(code, msg) {
    response.status.code(code)
    let res = JSON.stringify({
        "status": code,
        "msg": msg,
    })

    log(0, res)
    response.write(res)
    return res
}


// 记录数据流
function log(status, output) {
    let time = new Date().getTime()
    let dbTime = payload.get().headers["Databus-Time"]
    if (dbTime) {
        response.headers.add("Server-Timing", `DataBus;dur=${time - dbTime}`)
    }

    let startTime = payload.get().headers["Timestamp"]
    let timeDiff
    if (startTime) {
        timeDiff = time - startTime
        response.headers.add("Server-Timing", `RequestCost;dur=${timeDiff}`)
    }

    // 记录请求体
    payload.get().body = payload.get().body?.toString()

    // 记录登录日志
    SQL.push('system_sql', 'INSERT INTO log_dataflow (event_id, table_id, path, status, ipaddr, input, sql_stmts, output, user_info, blank) VALUES (?,?,?,?,?,?,?,?,?,?)',
        response.headers.get('X-Request-Id') || ex.suid().base58(),
        payload.get().query?.t,
        payload.get().path,
        status,
        payload.get().remote_addr.split(':')[0],
        JSON.stringify(payload.get()),
        SQL_STMTS.length && SQL_STMTS.length > 0 ? JSON.stringify(SQL_STMTS) : null,
        output,
        USER_INFO ? JSON.stringify(USER_INFO) : null,
        timeDiff
    );
}