function normalizeErrorData(data) {
    if (!data || typeof data !== 'object' || Array.isArray(data)) {
        return {}
    }

    const result = {}
    const keys = Object.keys(data)
    for (let i = 0; i < keys.length; i += 1) {
        const key = keys[i]
        const value = data[key]

        if (typeof value === 'undefined') {
            continue
        }

        if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
            result[key] = value
            continue
        }

        try {
            result[key] = JSON.stringify(value)
        } catch (_err) {
            result[key] = String(value)
        }
    }

    return result
}

function createAppError(statusCode, message, data) {
    const error = new ApiError(statusCode || 500, message || '服务器内部错误')
    error.statusCode = statusCode || 500
    error.status = statusCode || 500
    error.data = normalizeErrorData(data)
    return error
}

module.exports = {
    createAppError,
}
