function applyHttpMeta(e, code, msg) {
    const statusCode = code || 200
    const errMsg = msg || '操作成功'

    try {
        const res = e && typeof e.response === 'function' ? e.response() : null
        const headers = res && typeof res.header === 'function' ? res.header() : null

        if (headers && typeof headers.set === 'function') {
            headers.set('X-Status-Code', String(statusCode))
            headers.set('X-Err-Msg', encodeURIComponent(errMsg))
            headers.set('Access-Control-Expose-Headers', 'X-Status-Code, X-Err-Msg')
        }
    } catch (_err) {
        // Header injection failures should not break API responses.
    }

    return {
        statusCode,
        errMsg,
    }
}

function normalizePayloadData(data) {
    if (typeof data === 'undefined' || data === null) {
        return {}
    }

    if (data && typeof data === 'object' && !Array.isArray(data)) {
        return data
    }

    return {
        data: data,
    }
}

function success(e, msg, data, code) {
    const meta = applyHttpMeta(e, code || 200, msg || '操作成功')
    return e.json(meta.statusCode, normalizePayloadData(data))
}

function successWithToken(e, msg, data, token, code) {
    const meta = applyHttpMeta(e, code || 200, msg || '操作成功')
    const payload = normalizePayloadData(data)

    if (token) {
        payload.token = token
    }

    return e.json(meta.statusCode, payload)
}

function fail(e, msg, data, code) {
    const meta = applyHttpMeta(e, code || 400, msg || '操作失败')
    const payload = normalizePayloadData(data)
    payload.statusCode = meta.statusCode
    payload.errMsg = meta.errMsg
    payload.message = meta.errMsg
    return e.json(meta.statusCode, payload)
}

module.exports = {
    success,
    successWithToken,
    fail,
}

